Posts

Showing posts from September, 2012

scripting - String splitting python -

i trying parse file , split line in python. can parse file , load list. i trying take each line , split parenthesis, 'datediff(varchar(30),timestamp(3),timestamp(3))' reverse(text) checkcluster(int,int,int,int,int) declaredown(int) i trying extract parameters in side function so: ['varchar(30),timestamp(3),timestamp(3)','text','int,int,int,int,int','int'] however result getting is: ['varchar(30', 'text', 'int,int,int,int,int', 'int'] i believe because of bracket in varchar. there way split first occurrence , last occurrence of parenthesis? is there way split first occurrence , last occurrence of parenthesis? yes, use partition , rpartition . >>> s = 'datediff(varchar(30),timestamp(3),timestamp(3))' >>> s.partition("(") ('datediff', '(', 'varchar(30),timestamp(3),timestamp(3))') >>> s.partition("(")[2]

java - Casting Number to double primitive -

i'm trying access hashmap<string, number> via reflection: serializable obj; //here goes hashmap string name; ... return (double)obj.getclass().getdeclaredmethod("get", object.class).invoke(obj, name); but far got casting error caused line above: java.lang.classcastexception: java.lang.integer cannot cast java.lang.double indeed, map value accessed key name integer .so i've changed line to: return obj.getclass().getdeclaredmethod("get", number.class).invoke(obj, name).doublevalue(); but didn't work out either. got doublevalue() underlined "undefined type object" (but why object if have number.class?). i'm not sure casting rules i'm breaking. can someone, please, me if map entries have various number values ( integer , float , double ) need method return double value (primitive). ps it's not duplicate. question more general. thank input. forgot invoke returns object. the working code is: return ((num

api - Invalid Signature - Creating Flickr Photoset -

i'am trying hours valid api call flickr. following link build clojure program: " http://api.flickr.com/services/rest/?method=flickr.photosets.create&oauth_signature= {sig}&oauth_token={token}&oauth_consumer_key={key}&oauth_signature_method=hmac-sha1&oauth_timestamp={time}&oauth_nonce={nonce}&oauth_version=1.0&title={title}&primary_photo_id={photoid}&format=json&nojsoncallback=1" and message browser returns: oauth_problem=signature_invalid&debug_sbs=get&http%3a%2f%2fapi.flickr.com%2fservices%2frest%2f&format%3djson%26method%3dflickr.photosets.create%26nojsoncallback%3d1%26oauth_consumer_key%3d23xxxxxxxxxxx6e46a05ae55c4%26oauth_nonce%3de6u52xxxxxxxxxpphqner4e0j%26oauth_signature_method%3dhmac-sha1%26oauth_timestamp%3d13xxxxx06%26oauth_token%3d721xxxxxxxx503-356bxxxxxxxf66e%26oauth_version%3d1.0%26primary_photo_id%3d12345678%26title%3dphotoset-title calls method "flickr.photosets.getphotos&qu

java - Why can't the Integer.class object be added to a Collection<Class<Number>> object? -

this question has answer here: is list<dog> subclass of list<animal>? why aren't java's generics implicitly polymorphic? 12 answers i thought have quite understanding of generics can't figure out why compiler error here: collection<class<number>> ncs = new hashset<class<number>>(); ncs.add(number.class); //ok! ncs.add(integer.class); //compiler error here would nice if explain this. :) edit: understand why it's not possible add integer.class object collection> pointed out in this question . don't understand why example same. of course doesn't work: collection<? extends number> ns = new hashset<number>(); ns.add(new integer(1)); //compiler error here but does: collection<number> ns = new hashset<number>(); ns.add(new integer(1)); //ok

php - Symfony console language changed -

i trying learn symfony framework. when type bin/console doctrine:fixtures:load command console language changes japanese (i think) , result can not debug error. can please make symfony console print results in english? the following error getting running above command. j�│t␤␋⎽ ⎼␊⎽⎺┤⎼␌␊ °⎺⎼┐ ␋┼├␊┼├␋⎺┼▒┌┌≤ ┌␊°├ ␉┌▒┼┐ ��php p▒⎼⎽␊ ␊⎼⎼⎺⎼: ⎽≤┼├▒│ ␊⎼⎼⎺⎼, ┤┼␊│⎻␊␌├␊␍ '␊│├␊┼␍' (t_string), ␊│⎻␊␌├␋┼± 'Ï€' ␋┼ /⎻⎼⎺┘␊␌├⎽/└▒┴▒/⎽⎼␌/a⎻⎻b┤┼␍┌␊/d▒├▒f␋│├┤⎼␊⎽/orm/l⎺▒␍p⎼⎺┘␊␌├⎽.⎻␤⎻ ⎺┼ ┌␋┼␊ 9 p▒⎼⎽␊ ␊⎼⎼⎺⎼: ⎽≤┼├▒│ ␊⎼⎼⎺⎼, ┤┼␊│⎻␊␌├␊␍ '␊│├␊┼␍' (t_string), ␊│⎻␊␌├␋┼± 'Ï€' ␋┼ /⎻⎼⎺┘␊␌├⎽/└▒┴▒/⎽⎼␌/a⎻⎻b┤┼␍┌␊/d▒├▒f␋│├┤⎼␊⎽/orm/l⎺▒␍p⎼⎺┘␊␌├⎽.⎻␤⎻ ⎺┼ ┌␋┼␊ 9 [s≤└°⎺┼≤\c⎺└⎻⎺┼␊┼├\d␊␉┤±\e│␌␊⎻├␋⎺┼\f▒├▒┌e⎼⎼⎺⎼e│␌␊⎻├␋⎺┼] p▒⎼⎽␊ e⎼⎼⎺⎼: ⎽≤┼├▒│ ␊⎼⎼⎺⎼, ┤┼␊│⎻␊␌├␊␍ '␊│├␊┼␍' (t_string), ␊│⎻␊␌├␋┼± 'Ï€' ␍⎺␌├⎼␋┼␊:°␋│├┤⎼␊⎽:┌⎺▒␍ [--°␋│├┤⎼␊⎽ [fixtures]] [--▒⎻⎻␊┼␍] [--␊└ em] [--⎽␤▒⎼␍ shard] [--⎻┤⎼±␊-┬␋├␤-├⎼┤┼␌▒├␊] [--└┤┌├␋⎻┌␊-├⎼▒┼⎽▒␌├␋⎺┼⎽] [-␤≠--␤␊┌⎻] [-─≠--─┤␋␊├] [-┴≠┴┴≠┴┴┴≠--┴␊⎼␉⎺⎽␊]

c++ - Make new filetype use custom icon -

i designing new programming language, , want allow users embed custom icon in output binary file, not standard exe file. exe files allow custom icons (not .exe files use same icon). how can own binary files? if want provide different icons files same extension, need register icon handler shell extension. details, see this page in msdn. your handler need know how extract icon file , return explorer.

c - Linux System V IPC: Unable to initialize semaphore value -

i have created simple semaphore initialization example demo purpose: #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <unistd.h> #include <stdlib.h> int init_semaphore(int semid, int semnum, int initval) { union semun pack; pack.val = initval; return semctl(semid,semnum,setval,pack); } but getting error: error: aggregate ‘init_semaphore(int, int, int)::semun pack’ has incomplete type , cannot defined i not able understand why compiler throwing error. headers included properly. you have explicitly declare union semun yourself. per posix standard semctl() : the semctl() function provides variety of semaphore control operations specified cmd. fourth argument optional , depends upon operation requested. if required, of type union semun , which application shall explicitly declare : union semun { int val; struct semid_ds *buf; unsigned short *array;

Android custom imageview with zoom and scroll -

i trying create image view zoom , scroll. checked many solutions on internet , didn't accurate result. current imageview having scroll property.need add zoom. public class mapview extends imageview { private gesturedetectorcompat gesturedetector; private overscroller overscroller; private final int screenw; private final int screenh; private int positionx = 0; private int positiony = 0; public mapview(context context) { super(context); // need screen dimensions make sure don't on scroll image displaymetrics dm = getresources().getdisplaymetrics(); screenw = dm.widthpixels; screenh = dm.heightpixels; gesturedetector = new gesturedetectorcompat(context, gesturelistener); overscroller = new overscroller(context); } @override public boolean ontouchevent(motionevent event) { gesturedetector.ontouchevent(event); return true; } @override public void

Handle schema change in Google datastore with Go? -

i added new attribute go struct, persisted in datastore entity kind. i tried load entities using filter on new attribute: q := datastore.newquery("person").filter("employed =", false) this worked intended persons created after new attribute added. i had expected persons created before attribute added incleded in filter, didnt have attribute @ all, excluded filter. i have thought of 2 ways handle this: first load entities , filter in second step loop. adds complexity code. batch load , resave entities, adds property , sets false. have remember every time add new attribute. is there batter way handle these types of entity schema changes? the proper way re-save old entities if can afford it. you can use python map/reduce library update old entities. if want stick go can go simple batch processing using task queues & query cursors . in our python app prefer "in-flight hot update" approach whenever possible - new versio

Bash: check for multiple occurrences within a given time frame -

i looking way have script check multiple occurrences of line report true if happened in 5 or 10 minute interval anywhere in file. #!/bin/bash var1=$(/bin/grep -i 'string match' /var/log/logfile.log | wc -l) if [ "$var1" -ge 10 ]; echo " string match exceeded 10 times" exit 2 fi so basically, if see 10 or more string matches occur anywhere in logfile long occurred within 5 minutes of each other need change or add? fyi logfile date format looks this: 2016-06-01 18:58:00.307 i not sure 3 digit # appended end of date.

wordpress - String integration functions.php WPML -

hey guys trying translate last words of wp site. problem "read more" not translated. tried on wpml find solutin every time error 500 or text output not work. /* modify wordpress read more link add_filter( 'the_content_more_link', 'modify_read_more_link' ); function modify_read_more_link() { return '... <a class="more-link" href="' . get_permalink() . '">read more</a>'; } //* modify genesis content limit read more link add_filter( 'get_the_content_more_link', 'matchstick_more_link' ); function matchstick_more_link() { return '... <a class="more-link" href="' . get_permalink() . '">read more</a>'; } function matchstick_custom_excerpt_more( $more ) { return '... <a class="more-link" href="' . get_permalink() . '">read more</a>'; } and should insert <?php _e( 'read me', 't

C# Searching Through Different Groups of RichTextBoxes and Posting Them on CSV File -

building on information got last night, have 3 different groups of existing richtextboxes (meaning painted on form) called cbox#, vbox# , tbox# (the # indicates numerical value ranging 1 n cbox1, cbox2, etc ). cbox# , tbox# changes changes color white red or green while 'vbox#' contains kind of string (like 5.0 v). i set dummy data values , essentially, trying scan through current results , post them on excel file (in case, csv file). using (var file = new streamwriter("c:\\test\\" + datetime.now.tostring("yyyymmddhhmmssfff") + ".csv")) { file.write("com stat,"); file.write("trip stat,"); file.writeline("voltage"); string comread = null; string tripread = null; string voltread = null; cbox1.backcolor = color.green; cbox2.backcolor = color.green; cbox3.backcolor = color.red; cbox

php - FOS UserBundle User Manager - login after updateUser -

i ask whether package fos userbundle when add user, can log user manager? if so, in way? $usermanager = $this->container->get('fos_user.user_manager'); $user = $usermanager->createuser(); $user -> setusername('test'); $user -> setemail('test'); $user -> setplainpassword('test'); $user ->setenabled(true); $usermanager->updateuser($user, true);` ` problem solved. $loginmanager = $this->container->get('fos_user.security.login_manager'); $firewallname = $this->container->getparameter('fos_user.firewall_name'); $loginmanager->loginuser($firewallname, $user); thanks help

json - Unmarshall PubSub Request Data []bytes with Golang -

i have end-point receives data google pubsub request. per this repo , object so: type pushrequest struct { message struct { attributes map[string]string data []byte id string `json:"message_id"` } subscription string } the data field consistently formatted so: type data struct { key string `json:"key"` body string `json:"body"` meta map[string]interface{} `json:"meta"` } i can obvious unmarshal json request this: f := &pushrequest{} json.unmarshal(msg, &f) that leaves the []bytes field. can convert string, per docs messages = append(messages, string(f.message.data)) which doesn't help, since need struct. i can unmarshal array again: var m data json.unmarshal(f.message.data, &m) have tried changing field type in pushrequest struct data without success. blank... is there way can unpack things in single pass? doi

google maps - FETCH_ERROR on parse KMZ in WEB -

i have application features dynamic kmz on map. kmz needs updated every 60 seconds, wherefore url uses versioning feature: "?v=201606011903". earlier week kmz stopped appearing on map , error api returns "fetch_error". i'm intrigued as: there have been no changes in application; the generation of kmz working properly; tested kmz generated in feedvalidator , result valid kml 2.2 feed; curiosity: apparently there delay in acquisition or parse of kmz api. if try same kmz again after 3 minutes api returns correct results. doubt: there maximum time download or parse of kmz api? kmz analysis on feedvalidator script test: first change value of "v" , run. error "fetch_error" appear. wait 3 minutes , run same code (as same parameter). kmz should appear correctly. <html> <head> <style> html, body { height: 100%; margin: 0; padding: 0; } #map {

html - My CSS is not working with boostrap 3 -

i'm starting build webpage using bootstrap 3 (latest version) , reason can't seem add background image. the coding correct, files in proper folders, etc. finally decided create webpage exact coding difference css stylesheet not in css folder. refresh , background image appears. when move css file css folder, image gone. what happening? name of file correct, have added correct path , added other styling besides background image , seem working whether or not css file in or out of folder. html css file in css folder <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>home</title> <!--bootstrap css --> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

java - Creating own singly linked list to sort -

i'm trying create own singly linked list in java , use perform sorting. have access first node , next pointer used point next node. every node contains 2 fields x , y both integers. how add elements linked list without using built in methods , sort them using either quicksort or merge sort? how add elements linked list without using built in methods , sort them using either quicksort or merge sort? fast algorithms quicksort , mergesort depend on being able >>index<< array of elements being sorted; i.e. in operation sequences a[i] = a[j] . using linked list means random indexing o(n) operation. turn o(n log n) algorithm o(n^2 log n) one. if @ java's built-in sort methods (in various versions of java), see sorting linkedlist done by: copying list temporary array, sorting array, , clearing , copying array list. this efficient approach sorting large linked list.

html - Submitting Codemirror data with JavaScript not working correctly -

how can prevent needing submit form twice when using codemirror , submitting form javascript. happens is, changes make in codemirror textarea, stored temporarily in textarea (it has no name or id). if click submit button twice correct data sent avoid having click twice. here source code submit form: var ajax; var formdata = new formdata(); var fileupload = false; (i = 0; < e.elements.length; i++) { if (e.elements[i].type == "submit") { if (submitname == e.elements[i].name) { if (submit != null && submit.disabled) submit.disabled = false; submit = e.elements[i]; submit.disabled = true; formdata.append(e.elements[i].name, e.elements[i].value); } } else if (e.elements[i].type == "radio" || e.elements[i].type == "checkbox") { if (e.elements[i].checked) formdata.append(e.elements[i].name, e.elements[i].value); }

Could "Could not find relationship target File[]" be triggered by a cron resource? -

is possible cron resource type uses file resource type underneath? i'm asking because i'm trying debug error: could not find relationship target file[] and manifests apply particular node contain no file resource type (that haven't verified work on other nodes). however, contain questionable cron , when commented out, doesn't generate error. similar specified ncracker, seem there file resource being referenced somewhere. if wasn't directly part of cron commented out, cron { require => file[$somevar] } call elsewhere in code. that way used tie default resource behavior.

php - Symfony2 Templating renderResponse causing CPU usage to shoot up -

i have job loops through users , sends personalized email based on preferences. using templating engine in symfony2 generate html. basically runs in loop: public function gethtml($user) { $templating = $this->getcontainer()->get('templating'); $html = $templating->renderresponse( 'recommendation.html.twig', array( 'user' => $user ) )->getcontent(); return $html; } the problem cpu usage shoots 100% , takes longer , longer process each user. here data: took 5.4851469993591 seconds took 12.790720939636 seconds took 23.007503032684 seconds took 34.852293014526 seconds took 43.901736021042 seconds took 66.028288125992 seconds each line represents time taken process 100 users. first 100 users took 5 seconds, next 12 seconds, , on. any suggestions on can improve performance? it'll doctrine accumulating massive identity map of

bash - Subprocess in Python 2.7 -- issuing commands into an engine -

i'm new python, , i'm given engine in bash (which takes own unique commands command line prompt or file , exercises specific functionality). want subprocess through python. i'm able open engine subprocess.call(path, shell=true) , , manually interact / input commands, cannot figure out how script unique commands input engine through python, see outputs automatically. i've tried understand of documentation, so, verbose. ideally script of input commands in python, subprocess engine, , see output engine in python output. again, forgive me if sounds confusing. example, i've tried: p = subprocess.popen(path-to-engine, stdin = subprocess.pipe, stdout = subprocess.pipe, shell=true) p.stdin.write("some commands") p.stdout.readline() p.kill() but gives me exit code 0, , no output. you should use .communicate() instead of .kill() : import subprocess p = subprocess.popen( path_to_engine, stdin=subprocess.pipe, stdout=subprocess.pi

ios - How to access elements from an NSObject in swift? -

i've set variables object import uikit class speedtestresult: nsobject { var testtime: nsdate? } then in controller set object , pass class store it: testresult.testtime = nsdate() speedtestmanager().addtestresult(testresult) i need store object , access elements within in view later, have: import foundation class speedtestmanager : nsobject { var testresultarray = [nsobject]() func addtestresult(testresult: nsobject) { testresultarray.append(testresult) print("printing testresultarray: \(testresultarray)") } } but when try print the object printing testresultarray: [<projectname.speedtestresult: 0x127b85e50>] how access elements within object , store object , retrieve later use in view? class testresult : nsobject, nssecurecoding { var testtime: nsdate? override init() { super.init() } @objc required init?(coder decoder: nscoder) { self.testtime = decoder.decodeobjectfor

Maven multi-module web application (Hot swap) -

i have multi module web application. the structure is: parent | | - - child 1 | - - child 2 | - - web and web project depends on 2 child modules when using ide build project used ide building classes in web-inf/classes folder. nice web server noticed new classes , either restarted or hot deployed these files. maven seems have package whole thing scratch every time. i find way in maven such can avoid running mvn:clean mvn:install mvn:war:inplace. instead mvn:comile, , stuff there. i hope understand mean. testing web app extremely slow when have build project jars , run som war command before things updated. the web apps pom: <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelversion>4.0.0</modelversion> <parent> ... </parent>

swift - Why does my code return a bad access exception? -

i've got swift sprite kit project trying work on, whenever run game crashes on gameviewcontroller @ startup exc_bad_access code 1. here code: class gameviewcontroller: uiviewcontroller { @iboutlet var imagebanner: uiimageview? @iboutlet var textbanner: uilabel? @iboutlet var playbutton: uibutton? @iboutlet var sharebutton: uibutton? @iboutlet var infobutton: uibutton? var skview = skview() var scene = skscene() override func viewdidload() { super.viewdidload() print("view did load") skview = skview(frame: self.view.frame) print("1") scene = gamescene(size: skview.bounds.size) print("2") skview.showsfps = false print("3") skview.showsnodecount = false skview.ignoressiblingorder = true scene.scalemode = .aspectfill print("done") } i guess it's worth noting "done" logged in console. you should not create new skview . , why creating scene variable initiali

ios - Empty Pod Headers Folder after `pod install` -

my appname -> targets -> build settings -> search paths -> header search paths set to: "${pods_root}/headers/public" when run pod install , get: $ pod install analyzing dependencies downloading dependencies using alamofire (3.1.1) using alamofireimage (2.1.0) using datetools (1.7.0) using jgprogresshud (1.3.1) using locksmith (2.0.8) using swiftyjson (2.3.1) using tpkeyboardavoiding (1.2.10) generating pods project integrating client project sending stats pod installation complete! there 7 dependencies podfile , 7 total pods installed. but, headers directory still empty. the exact errors having can seen in earlier question has been answered without solving problem, making me realize question wrong: how tell app pod header files are? edit 1 i have tried workarounds such tactic in question: framework did not have cfbundleidentifier in info.plist asked, seems kick can down road $ gem uninstall cocoapods $ gem install cocoapods add things

ios - NSManagedObjectContextDidSaveNotification useless? -

i using core data while background contex, , wondering why advise use nsmanagedobjectcontextdidsavenotification merging background main context. created test-project 1 nspersistentstorecoordinator , main context , background context. here code fragment initalisation: - (nsmanagedobjectcontext *)managedobjectcontext { if (_managedobjectcontext != nil) { return _managedobjectcontext; } nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator]; if (coordinator != nil) { _managedobjectcontext = [[nsmanagedobjectcontext alloc] initwithconcurrencytype:nsmainqueueconcurrencytype]; [_managedobjectcontext setpersistentstorecoordinator:coordinator]; } return _managedobjectcontext; } - (nsmanagedobjectcontext *)backgroundcontext { if (_backgroundcontext != nil) { return _backgroundcontext; } _backgroundcontext = [[nsmanagedobjectcontext alloc] initwithconcurrencytype:nsprivatequeueconcurrencytype]; _backgroundcontext.persistentstorecoordinator = se

cors - Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not? -

i trying authorization using javascript connecting restful api built in flask . however, when make request, following error: xmlhttprequest cannot load http://myapiurl/login . no 'access-control-allow-origin' header present on requested resource. origin 'null' therefore not allowed access. i know api or remote resource must set header, why did work when made request via chrome extension postman ? this request code: $.ajax({ type: "post", datatype: 'text', url: api, username: 'user', password: 'pass', crossdomain : true, xhrfields: { withcredentials: true } }) .done(function( data ) { console.log("done"); }) .fail( function(xhr, textstatus, errorthrown) { alert(xhr.responsetext); alert(textstatus); }); if understood right doing xmlhttprequest different domain page on. browser blocking allows request in same origin securi

How to read x-death header of a RabbitMQ dead-lettered message using Spring Boot? -

i trying implement re-routing of dead-lettered messages described in answer . using spring config. have no idea on how read headers original routing key , original queue. following config: @configuration public class notifenginerabbitmqconfig { @bean public messagehandler handler(){ return new messagehandler(); } @bean public jackson2jsonmessageconverter messageconverter(){ return new jackson2jsonmessageconverter(); } @bean public messagelisteneradapter messagelisteneradapter(){ return new messagelisteneradapter(handler(), messageconverter()); } /** * listens incoming messages * allows multiple queue listen * */ @bean public simplemessagelistenercontainer simplemessagelistenercontainer(){ simplemessagelistenercontainer container = new simplemessagelistenercontainer(); container.addqueuenames(queue_to_listen_to.split(",")); container.setmessagelistener(messagel

java - How can I use "for" loop and "if" loop both together to verify the existence of xml elements in xml document -

i'm trying make login system. need check existence of xml elements ("username" , "password") in xml document. if match "username" , "password" need return true, otherwise false. use "for" loop go through entire document , use "if" loop validation. i'm using java , dom parser. xml document: <login> <user> <username>sunimal</username> <password>1111</password> </user> <user> <username>naveen</username> <password>852</password> </user> <user> <username>chamara</username> <password>12345</password> </user></login> java code: boolean = false; try { file inputfile = new file("c:\\users\\kavindu\\documents\\netbeansprojects\\chatserver2\\xml\\userrecord2.xml"); documentbuilderfactory dbfactory = documentbuilderfactory.newinsta

java - Memory allocated to main class executed from servlet? -

i have servlet execute class main method(), can typically start via command line. in web container tomcat, weblogic server, web container has own defined heap space , number of threads execute request sent web application. if start class main method() in servlet, memory , threads allocated class? when invoking method via calling myclass.main() (as stated in comment) not matter method called main - other method-invocation. such any memory used during execution allocated on tomcat's heap execution in thread processes servlet-request. servlet not continue processing until main() exits. the easiest way use storage not tomcat's heap spawn new vm-process via runtime.exec() , run program there. result in quite overhead starting vm can take while. if ok running in tomcat's vm want execute task in parallel servlet-processing have implement own thread-handling.

jsf - Need to update inbetween action in primefaces -

in scenario using poll , having 2 output text field render option showing data " waiting refresh " , " refresh happened " , when poll action starts need show "waiting refresh" , collect data end ,it may take few (seconds or minutes or hour) after getting data need update "refresh happened" poll action ends cycle every 30 seconds. how this ? **viewer java class :** public string pollaction() { pollcountrendered = false; requestcontext.getcurrentinstance().update("viewerformid:headerid"); requestcontext.getcurrentinstance().update("viewerformid:containerid"); try { thread.sleep(5000); } catch (interruptedexception ex) { system.out.println(ex); } pollcount++; system.out.println("poll action"); pollcountrendered = true; requestcontext

jquery - Fixed top row when sort in datatable -

Image
i'm building website storing files , here ui when sort, ".." row bottom row , it's undesirable effects. i've tried this solution seem likes used old api. can show me how fix it? in advance update here code initialize datatable var tablefolder = $('#tablefolder').datatable({ columndefs: [ {"width": "50%", "targets": 0}, {"width": "25%", "targets": 1}, {"width": "25%", "targets": 2} ], aasorting: [], deferrender: true, scrolly: 560, scrollcollapse: true, scroller: true, paging: false, info: false, searching: false, ajax: url, fncreatedrow: function (nrow, adata, idataindex) { $(nrow).attr('id', adata[3]); } }); this has answer @ datatables blog . add plugin page //cdn.datatables.net/plug-ins/1.10.16/sorting/absolute.js if want order datatable , keep

javascript - Prevent the click event while press the enter key when button in focus in Jquery -

please advise me, created form , press tab key focus button. if press enter key instead of mouse click event, jquery events triggers both keypress , click event. how can prevent click event. please try 1 : $("#buttonid").keypress(function(e){ if(e.keycode === 13){ e.preventdefault(); } });

sql server - When do we specify fill factor for DBCC DBREINDEX? -

i checked on google , found if fill factor 0 uses 100% space on index page. otherwise need specify fill factor. my questions experts are: should leave blank maximum index efficiency? i found in our databases fill factor 80, 85, 90, 100 mentioned of indexes. so, when should specify fill factor 80 or 90? select fill_factor,* sys.indexes fill_factor <> 0 the default fillfactor 100 out of box (if hasn't been changed). when fillfactor 0, dbcc dbreindex uses last value specified index. fillfactor designed improving index performance , data storage when index created, rebuilt, or defragged. setting fillfactor, specify percentage of space on each page filled data, reserving free space on each page future table growth. example, if fillfactor 80, 20% of each page left empty, providing space new records. when space used up, page split occurs. microsoft recommends use default fillfactor in cases. however, if know how table used, can modify it. fillfactor of

gdb - pretty printer help: object has no attribute -

i writing first pretty printer, have trouble. gdb 7.7. here c++ code debug: enum country { china, usa }; class foo { public: foo(int _v, enum country c) {v = _v; m_country = c;} ~foo() { v = -1; } int v; enum country m_country; }; int main() { foo f(10, china); return 0; } here printer: import gdb class fooprinter: def __init__(self, val): self.v = val def to_string(self): # because v integer, simpler way is: # return self.v['v'] v = "v=" + str(self.v['v']) f = self.m_country['m_country'] if (f == 0): c = "china" elif (f == 1): c = "usa"

securing a jquery ajax to php connection -

my ajax code is: $.ajax({ type: "post", url: "save.php", data: { name: $(this).attr('name'), value: $(this).val(), id: <?php if(!empty($_session['user'])) echo $_session['user'];?> } }); and in save.php i'm checking condition: if (empty($_server['http_x_requested_with']) || $_session['user']!=$_post['id']){ //then show error } is correct method prevent unauthorized call save.php? in general.. anything @ client side insecure. therefore, script may called @ time using set of parameters. protecting specific script therefore, need prepare @ server-side , verifies valid @ later point of time. let's call security-token . security-toke needs sufficiently long , random string. security-token need non predictable . in case, server-side application can source of token. save security-token user's session , pass along client. associ

php - how can I get email and password at the same time methop post laravel 5.2 -

i email , password when call authcontroller@login method there isn't in controller. my proyect : want save activity login , bad passwords , bad email , how many time user tried enter system , corrects logins of course . my model useractivity have attributes: email,password,datetime . create new variable , save useractivity->save() ; when call post method login. i use php artisan make:auth but in authcontroller.php found functions. function __construct function validator function create but got route php artisan route:list command post | login | | app\http\controllers\auth\authcontroller@login | web,guest | namespace app\http\controllers\auth; use app\user; use validator; use app\http\controllers\controller; use illuminate\foundation\auth\throttleslogins; use illuminate\foundation\auth\authenticatesandregistersusers; class authcontroller extends controller { /* |-------------------------------------------------------------------------- | regi

java - Why after retainAll() the list comes to be null although it should has elements in it? -

now can list a, list b. , want new list a-(intersection of , b). when intersection, []. list<map<string,string>> userdevices = clientdeviceservice.getuserdevice(userid); list<string> selecteddevices = new arraylist<string>(arrays.aslist(devices));//selecteddevices is------[stress0012,stress0014,] list<string> originaldevices = new arraylist<string>(); list<string> originaldevicesretain = new arraylist<string>();//copy operating for(map<string,string> originaldevid : userdevices){ originaldevices.add(originaldevid.get("devid")); } originaldevicesretain.addall(originaldevices); originaldevicesretain.retainall(selecteddevices); //originaldevicesretain [],and return false. originaldevices.removeall(originaldevicesretain); if(!originaldevices.isempty()){ } why originaldevices [] has no elements in it?

java - Multiple column IN clause spring data jpa -

is possible have multiple columns in in clause? @query(nativequery = true, value = "select * table (column1, column2) in (:column1, :column2)") list<table> findbycolumn1column2in(@param("column1") list<bigdecimal> column1, @param("column2") list<bigdecimal> column2);` expecting query this: select * table (column1, column2) in ((1,2), (3,4), (5,6)) no works sql in , , expect result in case? edited answer: perhaps looking this: select * table column1 in :column1 , column2 in :column2 :column1 , :column2 both lists, not enforcing coupling between them. if want compare couple, need change application's logic.

node.js - How do I use mongoose to connect to two different databases? -

i have 2 databases 1 affects other one, wanted see if there way connect 2 both dbs 1 model can associated other db other model can focus on diff db. currently models this: var mongoose, schema, moduser, objectid, project, bcrypt, salt_work_factor; mongoose = require('mongoose'); schema = mongoose.schema; objectid = mongoose.schema.types.objectid; project = require('../models/project.js'); bcrypt = require('bcryptjs'); salt_work_factor = 10; moduser = new schema({ email: { type: string, required: true, lowercase: true, index: {unique: true}}, password: { type: string, unique: true} }, {collection: "modusers"}); module.exports = mongoose.model('moduser', moduser); and in routes call mongoose top: var mongoose = require('mongoose'); mongoose.connect("mongodb://connect1"); i want able use in routes file function can make use of both dbs... how add second db , target both dbs - thinking maybe including th

.net - 3rd Part solution for Huge file uploading -

i looking third party solution allow user upload files of 10 gb (2 gb each file). please suggest third party solutions can implemented efficiency. i using .net. thank you. if need reliable large file transfers suggest consider integration bittorrent sync api . yes, not pure .net solution, bittorrent brings lot file transfer. without bit more details use case, can not comment whether fit solution in other aspects, purely file transfer worth looking at.

vb.net - Check before dataser make changes -

i use datagridview , populate using dataset follows: private getgeschaftdataset new dataset public function getdataset() dataset implements idal.getdataset dim strcon = new appsettingsreader().getvalue("connectionstring", gettype(system.string)).tostring() using con new sqlconnection(strcon) using cmd new sqlcommand("select * t_marke", con) con.open() ' create data adapter in method , throw away afterwards using getprojectsdataadapter = new sqldataadapter(cmd) getprojectsdataadapter.fill(getgeschaftdataset, "trial1") end using end using end using return getgeschaftdataset end function when user ends work save changes db this: public sub makechangesdataset() implements idal.makechangesdataset if not getgeschaftdataset.haschanges messagebox.show("no changes save", "

postgresql - Set value in select statement -

i have 2 views , b created other views (cant use rule on update instead). , b have same 3 columns text_1, text_2, count. till sql looks like: select a.text_1, a.text_2, coalesce(b.count,a.count) count left join b on a.text_1 b.text_1 , a.text_2 b.text_2; but need rule set value of count 0 of records text_1 text_2 in result of select statement above. i'm using views because use "create or replace..." statement. using make simpler , cast boolean integer avoids verbose case select text_1, text_2, coalesce(b.count, a.count) * (not text_1 = text_2)::int count left join b using (text_1, text_2)

elasticsearch - Cannot parse CSV file with Logstash -

i have issue importing csv file elasticsearch using logstash further processing in kibana. this logstash config file: input { file { path => ["/absolute_path_to_file/export.csv"] start_position => beginning ignore_older => 0 sincedb_path => "/dev/null" } } #filter { # csv { # columns => [ # "id", # "cislo_smlouvy", # "zdroj", # "produkt", # "sjednani", # "datum_odeslani", # "cas_odeslani", # "pojistovna", # "tarif", # "pojistnik", # "telefon", # "predmet_pojisteni", # "rz", # "pocatek_pojisteni", # "rocni_pojistne", # "urgence", # "stav" # ] # separ

r - How can I suppress Google's API warning when using ggmap with knitr? -

how can suppress google's messages when using ggmap knitr .rnw file? here code generate pdf .rnw: \documentclass{article} \begin{document} <<>>= library(ggmap) qmap("empire state building", zoom = 15, messaging = false, source = "google") @ \end{document} in resulting .pdf, following poorly formatted messages appear: map url : http://maps.googleapis.com/maps/api/staticmap?center=empire+state+building&zoom=15&size=%20640x640&scale=%202&maptype=terrain&sensor=false google maps api terms of service : http://developers.google.com/maps/terms information url : http://maps.googleapis.com/maps/api/geocode/json?address=empire+state+building&sensor=false google maps api terms of service : http://developers.google.com/maps/terms can suppressed (was hoping messaging = false this) or @ least formatted warnings don't run off page? thank you. you can supress messages code chunk using message = false <<

java - Jackson deserialize JsonIdentityReference (alwaysAsId = true) -

following on question: question here @jsonidentityreference(alwaysasid = true) , @jsonidentityinfo(generator = objectidgenerators.propertygenerator.class) works great serialization end, not when comes time deserialize since can't resolve object id reference. is there way deserialize? writing custom deserializer seems overkill. instead of custom deserializer, can use simple setter deserializer: public class container { @jsonidentityinfo(generator = objectidgenerators.propertygenerator.class, property = "id") @jsonidentityreference(alwaysasid = true) private foo foo; public foo getfoo() { return foo; } public container setfoo(foo foo) { this.foo = foo; return this; } @jsonproperty("foo") public void setfoo(string id) { foo = new foo().setid(id); } } example string of {"foo":"id1"} serialized method in jackson 2.5.2

javascript - how to focus a custom cell in table? -

i have table , rowselected,i want when user focusout on 4th td 6th td focus instead of td 5. var rowindex=$("#mycustomizedtable).attr('rowselected); var row=$("#mycustomizedtable tbody).find('tr')[rowindex]; var tds=$(row).find('td'); var colselected=$("#mycustomizedtable).attr('colselected'); console.log(colselected); for example : result '4' in console now,i want 6td focus. i write have not right answer. if(colselected==4) { $(row).find('td').eq(6).focus(); } how can done? you can refer below code help. here have added focusout listener input elements present in out <table> element. check if focusout happening 4th cell's input or not. , if happening there forcing focus in 6th cell's input box. hope guide achieve goal. $(document).ready(function(){ $("#mycustomizedtable t

c# - MVC5 POST form retrieves data from previous index -

i populated view model passed in controller. each loop generate hyperlink button should pass in guid. however, when clicked on button , initiated post request, guid belongs button of previous index. however, after checking element using chrome's inspection tool, button has correct guid attached it. when button clicked (posting), guid passed parameter belongs previous index's. for example: button (guid 1000) button b (guid 2000) button c (guid 3000) when click on button b, guid passed posting 1000, belongs button a. index.cshtml @foreach (var item in model) { <tr> <td> @html.displayfor(modelitem => item.patientname) </td> <td> @html.displayfor(modelitem => item.nric) </td> <td> @using (html.beginform("patient", "maincontroller", new { guid = item.patientid }, formmethod