Posts

Showing posts from May, 2015

python - Getting Selected Rows Count in QTableWidget - PyQt -

in python plugin , i'm developing, need retrieve number of selected rows in qtablewidget . can loop through each row of qtablewidget , check them whether selected or not. instead, there straightforward way selected rows count of qtablewidget in pyqt ? something like: qtablewidget.selectedrowscount() if want number of rows fully selected (i.e. when clicking on row header): len(tablewidget.selectionmodel().selectedrows()) but if want rows have at least 1 cell selected : len(set(index.row() index in tablewidget.selectedindexes()))

amazon sns - Empty payload when sending push notifications from AWS SNS -

i'am using gcm android app send push notification,when send message aws sns console receive notification payload parameter empty below: { "type": "callback", "source": { "pushtype": "gcm", "invocationapis": [], "bubbleparent": true, "showtraynotification": true, "enabled": false, "__propertiesdefined__": true, "singlecallback": false, "_events": { "callback": {} }, "focusapponpush": false, "debug": false, "showappontrayclick": true, "showtraynotificationswhenfocused": false, "apiname": "ti.module" }, "payload": "", "bubbles": false, "cancelbubble": false } to receive notification,i have written code:

java - Non-static variable cannot be referenced from a static context -

i've written test code: class myprogram { int count = 0; public static void main(string[] args) { system.out.println(count); } } but gives following error: main.java:6: error: non-static variable count cannot referenced static context system.out.println(count); ^ how methods recognize class variables? you must understand difference between class , instance of class. if see car on street, know it's car if can't see model or type. because compare see class "car". class contains similar cars. think of template or idea. at same time, car see instance of class "car" since has properties expect: there driving it, has engine, wheels. so class says "all cars have color" , instance says "this specific car red". in oo world, define class , inside class, define field of type color . when class instantiated (when create specific instance), memory reserved color

ios - Common function for alert view? -

i want show alertview in controller classes. have created common function show alert & respond it's action buttons. in commonfunctions.swift i have created 1 function below func showactionalertview(title:string,message:string,vc:uiviewcontroller) -> void { let alert = uialertcontroller(title: "warning", message: nslocalizedstring("alert_delete", comment: ""), preferredstyle: uialertcontrollerstyle.alert) alert.addaction(uialertaction(title: "yes", style: .default, handler: { (action: uialertaction!) in constant.commonfunction.showloader(withmessage: "loading") })) alert.addaction(uialertaction(title: "cancel", style: .cancel, handler: { (action: uialertaction!) in print("handle cancel logic here") })) vc.present(alert, animated: true, completion: nil) } and created protocol in commonfunctions.swift . protocol alertdelegate { func okaction(controller:uiviewcontroller) func can

gradle - Using Jacoco in eclipse -

i using eclipse buildship plugin. have gradle project in build.gradle follows: apply plugin: 'java' apply plugin: 'jacoco' version = '1.0' repositories { mavencentral() } dependencies { testcompile group: 'junit', name: 'junit', version: '4.11' } the project understand how should unit testing. want use plugin jacoco code coverage tool. following command : gradle clean test jacocotestreport now, need console write this. how should write command in eclipse? or there alternative gui way in eclipse + builship plugin ? i think best way see coverage in eclipse install eclemma plugin uses jacoco under hood. can right click on test class / test method coverage as... junit test

node.js - adding new element to the xml using node js -

var readline = require('readline'); var et = require('elementtree'); var xml = et.xml; var elementtree = et.elementtree; var element = et.element; var subelement = et.subelement; var fs = require('fs'); var root; var datanew, etreenew; var etree; var rl = readline.createinterface ({ input: process.stdin, output: process.stdout }); function createxml(root) { etree = new elementtree(root); var done = json.stringify(etree); console.log(done); rl.question('\nenter file name create xml: \n', function (d){ var xml = root.write({'xml_declaration': false}); console.log(xml); var newfile = fs.write(d,xml); console.log("\nxml file updated..!!\n"); }); } function getelements(subroot, numelements) { if(numelements > 0) { rl.question('\nenter element name: \n', function(name1) { rl.question('\nenter element data: \n', function (data

php - I can't print search result to MS Word -

i'm trying print search result ms word. it not working instead displays in same html page. here code: viewstucon.php <?php error_reporting(0); include("configsample.php"); ?> <?php //asuume exporttoword input button clicked. if(isset($_post["exporttoword"])) { header("content-type: application/msword"); header("content-disposition: attachment; filename=database_dump.doc"); header("pragma: no-cache"); header("expires: 0"); if ($_request["course"]<>'') { $search_course = " , restu_course='".mysql_real_escape_string($_request["course"])."'"; } if ($_request["from"]<>'' , $_request["to"]<>'') { $sql = "select * ".$settings["data_table"]." restu_year between '".mysql_real_escape_string($_request["from"])."' , '".mysql_real_escape_stri

javascript - HttpServletRequest can not get xhr request parameter -

i working spring , javascript. calling @controller xhrhttprequest object. i can see parameter(json string) chrome inspector, when call request.getparamter("id") returns null. calling part js function ajax(url, data, callback, method){ //data {"id":"system", "password" : "1234"} var httprequest; var afteraction = function(){ if(!httprequest) { console.error('can not find httprequest variable'); return; } if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { var responsedata = httprequest.responsetext; //alert(json.stringify(responsedata)); console.log('result of api call >>>', responsedata); if(typeof callback == 'function') { callback(json.parse(responsedata)); } } else {

c# - LINQ statement broke after upgrading to .NET Core 1.1 Preview 1 -

i have asp.net core application tracks work crews. workcrewmembers class contains crew members. has key workcrew class has clumsy list of timespan? fields specifying when crew starts working on specific days of week: sunstart, monstart, tuestart, wedstart, thustart, fristart, satstart . classes generated legacy database. have following code working happily in asp.net core 1.0.1 public class program { public static void main(string[] args) { using (dbcontext context = new dbcontext()) { var lstworkcrew = (from m in context.workcrewmembers m.workcrew.todaystarttime() != null select m.workcrewid).tolist(); console.writeline($"today {lstworkcrew.count} work crews"); } } } public partial class workcrew { public timespan? todaystarttime() { timespan?[] starts = { sunstart, monstart, tuestart, wedstart, thustart, fristart, satstart }; int dayofweek =

javascript - How to reveal multiple html? -

suppose that, got pseudocode: itemset1[apple,orange] itemset2[banana,potato] <div> <header> <h3>mylist</h3> </header> <ul> <li>itemset1[]</li> </ul> </div> <div> <header> <h3>mylist</h3> </header> <ul> <li>itemset2[]</li> </ul> </div> is there way letting me write once html code? <div> <header> <h3>mylist</h3> </header> <ul> <li>items</li> </ul> </div> and reveals twice first example(one itemset1 , 1 itemset2) can use evrything javascript or php prefer javascript there're 2 ways (or more?). rendering php or javascript . with php @ view for example, using foreach ($itemset1 $item) want. <div> <header> <h3>mylist</h3> </header> <ul> <?php foreach ( $itemset1

android - It's possible to download only one Json with retrofit2 for time? -

i'm using code download list of airports: final retrofit retrofit = new retrofit.builder() .addconverterfactory(gsonconverterfactory.create()) .addcalladapterfactory(rxjavacalladapterfactory.create()) .baseurl(airportservice.service_endpoint).build(); airportservice service = retrofit.create(airportservice.class); service.getairport() .subscribeon(schedulers.newthread()) .observeon(androidschedulers.mainthread()) .subscribe(new subscriber<list<airport>>() { @override public void oncompleted() { } @override public void onerror(throwable e) { e.printstacktrace(); } @override public void onnext(list<airport> airports) { airps = airports;

vb.net reporting hide tablix with expression -

Image
i have report have tablix within tablix shown here: the second tablix need hide when rows less 13. have following expression in group details property hidden : =iif(runningvalue(fields!blokno.value, countdistinct, "tablix5") >= 13, false, true) however, not work. header row still shows. doing wrong? for anyone's benefit. have added visibility expression tablix, apart group details hidden expression. worked. expression used : =iif(countdistinct(fields!blokno.value) >= 13, false, true)

jquery - Get Ajax PHP response for file upload form -

i've created upload form text fields create custom posts frontend in wordpress. the requst working, can't response message in ajax when file uploaded. if no file uploaded , text field set response. here ajax form: //upload-form.js _submit: function (event) { event.preventdefault(); this.$submitbutton.prop('disabled', true); var $formdata = false; var $form = this.$form; if (window.formdata) { $formdata = new formdata(); } var $files_data = this.$upload; if ($files_data.val() == '') { $formdata.append('fields', $form.serialize()); } else { $.each($($files_data), function (i, obj) { $.each(obj.files, function (j, file) { $formdata.append('files[' + j + ']', file); $formdata.append('fields', $form.serialize()); }) }); }

DatePicker in asp.net mvc visual basic -

helo, i'm working on small project visual studio 2015, asp.net 5, mvc. need know how develop in visual basic use datepicker enter dates using calendar in date fields. first of all, should understand use jquery in view. please refer ms document example using html5 , jquery ui datepicker popup calendar asp.net mvc

Android: Camera opens but doesn't save the taken shot, why? -

Image
i trying take picture , save in gallary app. far managed write following piece of code: public void sendmessages(view view) { intent intent = new intent(this, messagingadapter.class); startactivity(intent); } public void takepicture(view view) { intent cameraintent = new intent(mediastore.action_image_capture); cameraintent.putextra(mediastore.extra_output, getimageuri()); startactivityforresult(cameraintent, take_photo_code); } public uri getimageuri() { picno++; string storagefolderpath = environment.getexternalstoragedirectory() + "/cameraimages/"; string fullfilename = storagefolderpath + picno + ".jpg"; file newpic = new file(fullfilename); uri outputfileuri = uri.fromfile(newpic); return outputfileuri; } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { if (resultcode == 1) retur

How to stop getting zeros returned in python? -

this question has answer here: python division 10 answers hi there trying values simple fractions 1/225 or 35/75 keeps returning zeros? appreciated! mymatrix=[[0,1,1],[1,0,1],[1,1,0]] uu=len(mymatrix) initials_ss=[[150],[300],[100]] #your initial population size suceptibles initials_zz=[[5],[15],[555]] #your initial population size zombies initials_rr=[[0],[0],[0]] #your initial population size removed s_n=np.matrix(initials_ss) #initial value suceptibles vector z_n=np.matrix(initials_zz) #initial value zombie vector r_n=np.matrix(initials_rr) #initial value removed vector z_nn=np.array(initials_zz) ss=np.sum(s_n,axis=0) zz=np.sum(z_n,axis=0) rr=np.sum(r_n,axis=0) n=ss+zz+rr nn=1/n[0] tt=np.zeros((uu,uu),int) np.fill_diagonal(tt,nn) print(tt) print(nn) u=np.diag(z_n[:,0]) t=nn*(u*s_n) print(t) so when try find nn matrix filled zeros on diagonals s

Google Adwords + Analytics without a website -

Image
i haven't finished website yet, want play google adwords. how link google adwords google analytics if haven't website? google provides ga demo account , if follow link manual demo ga account won't see options on 5th step:

java - Trying to create a DvbBufferedImage but its width and height are 0 -

i'm trying create fade-in animation using dvbbufferedimage bd-j application changing alpha value of images, doublebuffer = new dvbbufferedimage(1920, 2180, dvbbufferedimage.type_advanced); but after creates buffer, width , height 0 , when i'm trying graphics: dvbgraphics buffergraphics = doublebuffer.creategraphics(); it returns null. after that, want draw images onto buffer , nullpointerexception . have , suggestion? think related libraries, because when replaced dvbbufferedimage bufferedimage using code: protected bufferedimage bufimage = new bufferedimage(1920, 2180, bufferedimage.type_int_argb ); it says : the constructor bufferedimage(int, int, int) undefined i mention i'm using customized eclipse developing bd-j applications , java version jre1.8.0_77 . classes used application listed below: basis.jar btclasses.zip j2me_xml_cdc.jar javatv.jar jsse-cdc.jar pbp_1_0.jar sonicbdj.jar your appreciated on problem, in advance!

java - How to handle exception thrown from ExceptionHandler in controller with ExceptionHandler in ControllerAdvice? -

i have custom exceptions extending exception (myexception1, myexception2, myexception3) @controller public class mycontroller { /* method throwing myexception1 method throwing myexception2 method throwing myexception3 */ @exceptionhandler(myexception1.class) public void handlemyexception1(exception ex){ //do throw ex; } @exceptionhandler(myexception2.class) public void handlemyexception2(exception ex){ system.out.println("exception logged inside controller") } } @controlleradvice public class myglobalexceptionhandler { @exceptionhandler(exception.class) public void handleallexception(exception ex){ system.out.println("exception logged outside controller"); } } intention: log myexception1 controller advice log myexception2 inside handler in controller log myexception3 controller advice myexception2 , myexception3 working intended mye

java - Thread-safety of javax.servlet.Servlet#getServletConfig() -

i wondering why calling javax.servlet.servlet#getservletconfig() thread safe: if check implementation in javax.servlet.genericservlet servlet api 3.0.1, see following: package javax.servlet; // lines omitted public abstract class genericservlet implements servlet, servletconfig, java.io.serializable { // lines omitted private transient servletconfig config; // lines omitted public void init(servletconfig config) throws servletexception { this.config = config; this.init(); } // lines omitted public servletconfig getservletconfig() { return config; } // lines omitted } the field config written in init(servletconfig) without synchronization, locking or config being volatile, while getservletconfig() called anytime later worker thread of servlet container. took quick tomcat/catalina code base, see no indication of servlet container performing magic, guarantee thread safe access field config through getservletconfig

How to add a folder to an android project sourceset from a gradle plugin -

i'm writing plugin gradle, generate classes android projects. i generate classes in projects src/gen/java folder, don't want them mixed real source code. from project's build.gradle config, can add make build tools see generated classes : android { sourcesets { main { java { srcdir 'src/gen/java' } } } } the problem want plugin set automatically. plugin tried followings : public class myplugin implements plugin { @override public void apply(project project) { // ... // test 1 : doesnt work project.android.sourcesets.main.java.srcdirs += "src/gen/java" // test 2 : doesnt work project.android.sourcesets { main { java { srcdir 'src/gen/java' } } } } } each time plugin works, folder still not seen compiler , can't find generated classes when compiling. 1 know of way plugin ?

java - IDP Initiated SSO Implementation in existing App -

i have existing application , of sudden have been given task implement idp initiated sso. there url idp clicking on asks me login idp provided credentials, after success login route moves our application , task start identify user , give proper access. have certificate provided our idp. how can achieve this? application spring mvc java application.i using jboss 7. havent done similar thing before. can please give step step clear picture on this? saw spring saml extension couldnt understand integrate existing app. in regard highly appreciated. idp-initiated sso idp-initiated sso post binding if user not have valid local security context @ idp, @ point user challenged supply credentials idp site, idp.example.org. the user provides valid credentials , local logon security context created user @ idp. the user selects menu option or link on idp request access sp web site, sp.example.com. causes idp's single sign-on service called. the single sign-on service builds

javascript - Using Jade features with gulp-changed? -

when make changes .jade files want gulp task run file, not files. i'm using gulp-changed . it's working fine, until make changes files affect global layout, eg _header.jade , _layout.jade . when make changes files nothing happens. layout files have _ before title. how can solve issue? here gulpfile lines gulp.task('jade', function() { return gulp.src('dev/templates/**/!(_)*.jade') .pipe(plumber({ errorhandler: onerror })) .pipe(changed('public', {extension: '.html'})) .pipe(jade({ pretty: true, })) .pipe(gulp.dest('public')) .pipe(browsersync.reload({ stream: true })); }); gulp.task('watch', function() { gulp.watch('dev/templates/**/*.jade', gulp.series('jade')); }); first thing refactor out jade compilation task separate function. allows parameterize jade compilation can run on 1 or more files of choice: function compilejade(files)

generics - TypeScript compiler confused with large inheritance/extension chain -

i have following (reasonably complex) extension chain. minimal reproducible example of problem (obviously classes have behavioural implementations in application). export class basemodel { public somebasemodelmethod(): void { } } export class baseview { public somebaseviewmethod(): void { } } export class collectionview<tchildview extends baseview, tmodel extends basemodel> extends baseview { public somecollectionviewmethod(): void { } } export class itemview<tmodel extends basemodel> extends baseview { public setitem(model: tmodel): void { } } export interface igridview<tchildview extends itemview<tmodel>, tmodel extends basemodel> extends collectionview<tchildview, tmodel> { somegridviewmethod(): void; } export class gridview<tchildview extends itemview<tmodel>, tmodel extends basemodel> extends collectionview<tchildview, tmodel> implements igridview<tchildview, tmodel> { publ

Mysql select to php string -

i have football site. player can have these results: 0, 1 or 3 (loss, draw, win) i want see results player got in last 3 matches. want add result (should number combined 3 possible results mentioned before) this code: $result = mysql_query("select * events_regged result not null , registrant_name='john' order id desc limit 3") or die(mysql_error()); while($row = mysql_fetch_array( $result )) { $form = $row['result']; echo $form; if ($form == '333') {echo 'won 3 times in row';} } the problem here 3 times number 3 , not number 333. think not need ' while ' statement here. how can it? $result = mysql_query("select * events_regged result not null , registrant_name='john' order id desc limit 3") or die(mysql_error()); $maxwins = 0; while($row = mysql_fetch_array( $result )) { $form = $row['result']; if ($form==3) $maxwins++; else $maxwins = 0; if ($maxwins

knockout.js - knockoutjs - accessing $parent/$root inside foreach binding -

here plunker code working on. have defined vm looks this. var employee = function(fname,lname){ var self= this; self.fname = ko.observable(fname); self.lname = ko.observable(lname); self.selectedelement = ko.observable('default value'); } var vm = function(){ var self = this; self.employees = new ko.observablearray([]); self.selectedelement = ko.observable(-1); var e1 = new employee('f1','l1'); var e2 = new employee('f2','l2'); self.employees.push(e1); self.employees.push(e2); }; ko.applybindings(vm,container); and code display list of employees <body id="container"> <h1>empoyees</h1> <div> <div data-bind="foreach: employees"> <h4 data-bind="text: 'employee' + $index()"></h4> <span>first name :</span> <span data-bind="text: fname"></span>

angularjs - 'angular package is missing' when running 'meteor test' -

i'm trying create tests meteor app using practicalmeteor:mocha run angular package missing when loading page. command running start: meteor test --driver-package practicalmeteor:mocha --port 3100 angular imported in main js file , running meteor app works fine. cause of this?

yii - Deploy a project in local machine server using Docker -

hello studying docker our new version of our erp system. have ubuntu 16.04 lts server in production have windows 7 os. dont have idea how deploy system. our consultant gave me idea deploy using docker. don't know configuration of docker in local deployment. project developed using yii 2.0 can me ? thanks well if asking if possible develop system in php in ubuntu , deploy in windows 7 using docker. yes possible. although in windows 7 production, not right os production. , docker run there using docker toolbox. i recommend go official docker page information. the docker way ensure if thing works in dev box work in system minor adjustments. regards

asp.net mvc - C#: Random partial loss of values saved in Session -

i got single page application heavily accessed simultaneously around 150 users through ipad or samsung tabs. in scenarios (5-10 of 150) session variables lost (not all). firstly thought there must erratic code might resetting session value couldn't find such instance. have verified not app pool recycle maximum worker process setting app pool sessoin.abort explicitly setting session in code some more info: asp.net mvc, backbone server memory: 16 gb db stored on separate server session state timeout: 300 authentication mode: forms now want know if possible session variables might lost due combination of high user load, multiple reads, number of ajax requests or else unexpected this. or other pointers towards should next resolved. thanks, ravi

How to access and display all data from list using AngularJS -

i have started learn angularjs. getting familiar of working lists. know how access , display data list. how can company name list clients , display in html code? , how can slug list companylist , display in html code? i display list in table shown under: 1 brett software engineer apple 2 steven database administrator google here code: controller.js var controllers = angular.module('myapp.controllers', []) controllers.controller('mycontroller', function ($scope) { $scope.clients = [{ name: 'brett', designation: 'software engineer', company: { name: 'apple' } }, { name: 'steven', designation: 'database administrator', company: { na

javascript - write a function that returns an array of all the values of all the keys it corresponds to -

i want create 1 function can called return array containing values of each object. e.g. function find ("firstname") returns ["virginia", "zadie", "jane", "bell"] an explanation great too, i'm incredibly new programming , trying learn. thank you var writers = [ { firstname: "virginia", lastname: "woolf", occupation: "writer", age: 59, alive: false }, { firstname: "zadie", lastname: "smith", occupation: "writer", age: 41, alive: true }, { firstname: "jane", lastname: "austen", occupation: "writer", age: 41, alive: false }, { firstname: "bell", lastname: "hooks", occupation: "writer", age: 64, alive: true }, ]; you can create function using map() method. var writers = [ { firstname: "virginia&

asp.net - ASP dot net core -

i'd know how specify routes in dot net core. example, have method, gets 1 argument(id), , returns user. method available through link (api/user/1). so, question how make method link -"api/user/1/profile" id , returns relevant id. necessary make 2 methods, or separate them , specify routes? using attribute based routing, can done this. [httpget("{id:int}")] public async task<iactionresult> getuserbyid(int id) {} [httpget("{id:int}/profile")] public async task<iactionresult> getuserprofilebyid(int id) {} more information on routing can found @ link. https://docs.asp.net/en/latest/fundamentals/routing.html

ssl - Google Cloud Platform does not recognise me as domain owner -

i have custom domain associated appengine application. it listed in google cloud platform, appengine settings, custom domains , indeed works. want enable ssl domain. problem: won't let me upload ssl certificate, saying not owner of domain. however, in webmaster central indeed listed owner of domain. verified 2 methods, meta-tag , html file. domain appears there property. how can convince google cloud platform indeed owner of domain let me upload ssl certificate?

bulkinsert - Want to bulk import from txt file into temporary table in SQL Server 2012 -

i keep getting error: parse error @ line: 1, column: 1: incorrect syntax near 'bulk'. the following text. using test file 2 rows in correct format rule out causing issue. create table #tabled1 ( vehicleid bigint, speed decimal(9,6), latitude decimal(9,6), longitude decimal(9,6), direction smallint, gpsquality tinyint ) go bulk insert #tabled1 'c:\users\michael.mccarthy\documents\test.txt' ( fieldterminator = '/t', rowterminator = '/n', keepnulls ); go use query. declare @query varchar(1000) set @query ='bulk insert #tabled1 "c:\users\michael.mccarthy\documents\test.txt" with( fieldterminator = ''\t'', rowterminator = ''\n'' )' exec (@query) select * #tabled1

android - Write to directory seen when connecting to PC -

i've got little android app written friend (nothing complex, extracts data phone csv) works fine, except output file gets written directory returned getexternalfilesdir() , rather deep in file system average user hold of. when plug phone laptop/pc via usb, mounts external drive. there way app write directory? thanks when plug phone laptop/pc via usb, mounts external drive. there way app write directory? yes, insofar environment.getexternalstoragedirectory() . equivalent of saying "i going write c: drive" on windows. dominant approach in 1996, came our senses , stopped cluttering root of drive files. a middle ground option put file in 1 of environment.getexternalstoragepublicdirectory() locations, such directory_downloads (if minsdkversion 8 or higher) or directory_documents (if minsdkversion 19 or higher).

What is the meaning of <%%= in Ruby on Rails? -

i cannot find anywhere in project working with. doesn't work in same way <%= (i tried change), can't understand difference. <span class="option-content" placeholder="<%=t('pages.edit.option')%>"> <%%= content %> </span> in short, erb processes double-percent marks single-percent marks. it looks you're using 1 layer of erb templates generate layer of erb templates. the first layer of erb doesn't need variable called content , t method: <span class="option-content" placeholder="<%=t('pages.edit.option')%>"> <%%= content %> </span> that first layer rendered produce second layer: <span class="option-content" placeholder="edit"> <%= content %> </span> as can see, erb template. expect else, later on, takes second erb , uses render like: <span class="option-content" placeholder=&quo

android - do I have to use a service for a socket in a thread going in background mode -

i have app doing many things , running thread listen port using socket. want able switch app (for ex email) still app continue listen port. i suppose have use service? also want listen next incoming request. believe have use bind mechanism re-run through socket.accept() code? a service continue run if app closed. yes, service way go. can bind service when app opens can communicate between service , app. also want listen next incoming request. believe have use bind mechanism re-run through socket.accept() code? you dont necesarily need bind this. service can listen incoming requests itself. do note service not run on seperate thread if want intensive work, consider spawning different thread inside service. can use intentservice handle threading. can run 1 intentservice if need multiple services, normal service better choice. also read: https://developer.android.com/guide/components/services.html and: https://developer.android.com/reference/android/app

Rails/RSpec: 'Travel' time helper is not available in feature specs? -

i tried use rails' time helper method travel in 1 of feature specs: scenario 'published_at allows set publishing date in future' magazine_article.update_attribute(:published_at, time.now + 1.day) expect { visit magazine_article_path(magazine_article.magazine_category, magazine_article) } .to raise_error(activerecord::recordnotfound) travel 2.days visit magazine_article_path(magazine_article.magazine_category, magazine_article) expect(page).to have_content('super awesome article') end end it's giving me this: nomethoderror: undefined method `travel' #<rspec::examplegroups::magazinearticles::asuser::viewing:0x007f84a7a95640> what missing? http://api.rubyonrails.org/classes/activesupport/testing/timehelpers.html in order use these helpers have include them tests. you can either including single test suit: describe myclass include activesupport::testing::timehelpers end or globally: rspec.conf

data type conversion - PHP function to safely return a float from string -

let's have form ask product's price. basically, don't consider case user adds thousands comma, is: 1,000.00 or 1,000,000.00 i consider case user inputs 1000.00 or 1000,00 or 1000000.00 never 1,000.00, or 10,000,000.00 or, worst, 10.000.000,00 i came function. function getprice($price) { if (is_string($price)) { if (strpos($price, ",") !== false) { $price = str_replace(',', '.', $price); } } return (is_numeric($price)) ? floatval($price) : false; } do consider safe function? can point improovements? you function looks ok me except last line floatval . my main consideration approach php not represent float correctly to: floatval , casting float or arithmetic operations float variables. for example php may convert 10000.00 9999,99 depending on precision set. (you can read more here http://php.net/manual/en/language.types.float.php ) if need prices arithmetic calculations after parsi

Pandas plotting bar -

plots = '' fig = '' plots = userdemo.gender.value_counts().plot(kind='bar', fontsize = '8') print userdemo.gender.value_counts() fig = plots.get_figure() fig.savefig('c:\\users\\user\\project\\reports\\genderbar.jpg') plots1 = '' fig1 = '' print userdemo.age_range_desc.value_counts() plots1 = userdemo.age_range_desc.value_counts().plot(kind='bar', fontsize = '8') print userdemo.age_range_desc.value_counts() fig1 = plots1.get_figure() fig1.savefig('c:\\users\\user\\project\\reports\\agerangebar.jpg') plots2 = '' fig2 = '' plots2 = userdemo.occupation_desc.value_counts().plot(kind='bar', fontsize = '8') print userdemo.occupation_desc.value_counts() fig2 = plots2.get_figure() fig2.savefig('c:\\users\\user\\project\\reports\\occupation.jpg') output: the output when print seems ok. when bar graphs created, first 1 fine subsequent ones characteristics of first gr

selenium - Getting java.lang.ClassCastException while trying to access element in the list -

sample code: public class { list<webelement> itemlist = new arraylist<webelement>(); public list<webelement> getitemslist() { itemlist = (driver.findelements(by.xpath("<some valid xpath>"))); return(itemlist); } } public class b { hp = new a(); public void subscribe() { hp.getitemslist().get(0).click(); } } i creating list of webelements on page in class , in class b trying click on first element. on execution getting below exception: > java.lang.classcastexception: java.lang.stackoverflowerror cannot cast java.lang.exception issues has thing findelements because when added elements using findelement method list manually in code, code working fine. in below example have commented findelements line , instead added elements manually, code working fine. public class { list<webelement> itemlist = new arraylist<webelement>(); public list<webelement>

silverlight 5.0 - EF 4 to EF 5 Database Authentication -

i have application developed using ef4, .net 4.5, silverlight 5, ria services. i want upgrade ef4 ef5, lot of differences specially on dbcontext. i using custom database authentication in ef4 implementing iauthentication interface in authenticationdomainservice class , use extended webcontextbase class on client. i don't know equivalent these steps on ef5 don't have domainservice class nor authenticationdomainservice class. can give me directions resolve issue!! i not getting domainservice class due absence of wcfria.entityframework.5.0.0.1 package. i have install , can have authentication created. hope can else.

swift3 IOS google plus login not working -

when try integrate google plus login in swift 3.0, it's not return in app. can please provide working script code. in swift 2.0 , previous versions google plus login working. may google need update swift 3.0 code snippet. thanks, lakshman

mysql - how to delete from one table where count less than? -

i have 2 tables. i use query find number of occurences of field 1 table in table select t.id, t.tag_text, count(*) cnt sms s, template t s.id_template=t.id group t.tag_text order cnt desc how can delete rows template if occure in sms less 5 times example? mean if count less 5. use mysql. delete template id in ( select id_template sms group id_template having count(*) < 5 )

shockwave - PowerPoint Flash properties missing from template -

Image
i have powerpoint templates behaves strange in regards shockwave flash objects . when inserting shockwave flash object in either template master or in slide in document created template, blank properties tool window when open properties object. if start powerpoint , insert template in default created slide, properties present should be. what cause this, , how (if possible) can fix template? the template use contains password protected macros. while don't see why should matter, suspect does. if mere presence of password protected macros causing this, you'd think problem go away when presentation saved , macros lost. yet problem persists in presentation, after macros gone. i use following procedure inserting object: activate developer tab. in developer tab, in control group, choose more controls . from list of controls, choose shockwave flash object , click ok . draw object slide or layout-master. right click object , choose properties . this show p

java - How to add listener for database changes in Hibernate? -

how can add listener row changes insertion, updation, deletion in hibernate. you can use jpa listeners @postupdate , @postpersist , @postremove (these portable across orm frameworks) , can here jpa spec. the postpersist , postremove callback methods invoked entity after entity has been made persistent or removed. these callbacks invoked on entities these operations cascaded.

Ruby duplicate an object with modified params -

i have ruby object say def initialize(args={}) @name = args[:name] ... end my_cat = cat.new(name: 'mittenz', age: 3, type: 'cheshire') i need duplicate within object option input different parameter, somehting this: class catcopyist def initialize(args={}) @my_cat = args[:cat] # my_cat object above passed here end def copy_cat another_cat = @my_cat.dup.merge(type: 'siamese') return another_cat end ... end i need blending copied object new parameter. you can use object#instance_variable_set override older variables. class cat attr_reader :name, :type, :age def initialize(args={}) @name = args[:name] @age = args[:age] @type = args[:type] end def to_s "#{name} (#{type} - #{age})" end def dup(args={}) new_cat = super() args.each do|var, value| new_cat.instance_variable_set(:"@#{var}", value) end new_cat end end mittenz = cat.new(name: 'mi

javascript - number input numeric only -

this question has answer here: html text input allows numeric input 53 answers i have project want numbers input i'm using input of type number allows decimal seperators etc. how prevent use of , . , e . i have looked around , couldn't find 1 gave desired result, sinds either didn't block decimal inputs, or allow user still paste in field. i have javascript , jquery can use, not want use external librairy. if able me appriciated. function limitkeys($id) { $field = document.getelementbyid($id); $value = $($field).val(); //if value contains multiple e , or . value no longer valid , gives me blank console.log($value); $regex = /[^\d]/; $val = $value.replace($regex, "");// cant replace in blank console.log($val); //$($field).val($val); } $('.number-only').keypress(function (event) { //sinds it&

angularjs - Token authentication and regular resources -

i have django backend angular frontend. backend exposes rest api, , frontend uses token authentication. i have problem when serving ordinary resources, such files created in server , supposed downloaded client. when browser accesses these resources (through <img> tag or <a href=...> ), token not added http headers , backend doesn't authenticate user. i can work both tokens , cookies, hope there's easier , more straightforward.

java - org.springframework.beans.MutablePropertyValues.add(Ljava/lang/String;Ljava/lang/Object;)Lorg/springframework/beans/MutablePropertyValues -

Image
i new spring, using spring 4 once war deployed jcs-saas (cloud) getting belows error : [2016-11-08t12:50:06.686+00:00] [incident_error] 1 [incident 22 created problem key "bea-101216 [http]"] [2016-11-08t12:50:06.547+00:00] error [failure occurred in execution of deployment request id '3634255956252836' task '71'. error is: 'weblogic.application.moduleexception: [http:101216]servlet: "pepsiservlet" failed preload on startup in web application: "test4.war".[ org.springframework.beans.factory.beandefinitionstoreexception: unexpected exception parsing xml document class path resource [pepsiservlet-context.xml]; nested exception java.lang.nosuchmethoderror: org.springframework.beans.mutablepropertyvalues.add(ljava/lang/string;ljava/lang/object;)lorg/springframework/beans/mutablepropertyvalues; pom.xml <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/200