Posts

Showing posts from February, 2010

node.js - Multiple authentication controllers on one route -

i trying add 2 authentication controllers 1 route. example, trying make: router.route('/employees') .get(authcontroller1.isauthenticated, mycontroller1.get1) .get(authcontroller2.isauthenticated, mycontroller2.get2); the isauthenticated function follows: exports.isauthenticated = passport.authenticate('basic', { session: false }); does know how possible? thanks, daniel route: router.route('/employees') .get(authcontroller.isauthenticated1, authcontroller.isauthenticated2, mycontroller1.get1) authcontroller : exports.isauthenticated = function(req, res, next) { // authentication code if (!req.isauthenticated) { // not authenticated return res.status(401).send({ message: 'user not authenticated' }); } next(); }; exports.isauthenticated2 = function(req, res, next) { // authentication2 code if (!req.isauthenticated2) { // not authenticated

Does R optimise the order of matrix multiplications? -

if multiplying 3 matrices together, abc. depending on size of matrices may more efficient perform either (ab)c or a(bc). if evaluate: a %*% b %*% c will optimised in anyway? thanks colonel beauvel setting me on right path - test it. using example wikipedia , scaling suitably: > mult <- 100 > ar <- 10 * mult > ac <- 30 * mult > br <- 30 * mult > bc <- 5 * mult > cr <- 5 * mult > cc <- 60 * mult > > <- matrix(rnorm(ar * ac), ar, ac) > b <- matrix(rnorm(br * bc), br, bc) > c <- matrix(rnorm(cr * cc), cr, cc) > > system.time({ (a %*% b) %*% c }) user system elapsed 3.01 0.00 3.01 > system.time({ %*% (b %*% c) }) user system elapsed 25.34 0.03 25.37 > system.time({ %*% b %*% c }) user system elapsed 2.98 0.00 2.98 > system.time({ t(c) %*% t(b) %*% t(a) }) user system elapsed 25.61 0.03 25.64 incidently - r evaluates left righ

java - how to show autocomplete in gwt in tabular format with multiple column? -

following code shows 1 column in autocomplete want shows data in tabular foramte multiple column[in short want show suggestion box in tabular formate]. how can that? in advance please suggest anything.. flowpanel panel = new flowpanel(); initwidget(panel); final bulletlist list = new bulletlist(); list.setstylename("token-input-list-facebook"); final listitem item = new listitem(); item.setstylename("token-input-input-token-facebook"); final textbox itembox = new textbox(); itembox.getelement().setattribute( "style", "outline-color: -moz-use-text-color; outline-style: none; outline-width: medium;"); final suggestbox box = new suggestbox(getsuggestions(), itembox); box.getelement().setid("suggestion_box"); item.add(box); list.add(item);

python - takes exactly 1 positional argument (0 given) -

i'm trying make every time click button can run different. counter = 0 def b_c(counter): counter = counter + 1 if counter == 1: print("1") elif counter == 2: print("2") else: if counter == 3: print("3") but get typeerror: b_c() takes 1 positional argument (0 given) try this: counter = 0 def b_c(): global counter counter += 1 if counter == 1: print("1") elif counter == 2: print("2") else: if counter == 3: print("3") b_c() b_c() b_c() output: 1 2 3 first thing: python case sensitive, counter not equal counter. , in function can use global counter don't need pass counter button click.

javascript - Catching the response of the iFrame once receiving the response -

i posting message iframe. iframe returns response boolean. need catch response when response arrives parent window iframe. code not working. idea onthis? iframe <iframe id="opiframe" src="https://localhost:9443/oauth2/session" > </iframe> i'm sending message iframe periodically var iframe = document.getelementbyid("opiframe"); setinterval(function(){ message ='test' ; console.log('request rp: ' + message); iframe.contentwindow.postmessage(message,"https://localhost:9443/oauth2/session"); },6000); what need receive response of iframe periodically. code working. added eventlistener iframe below. iframe.addeventlistener("message",test,false); function test(event){ alert("test"); } but not firing periodically it simple: added listener on iframe (as element of parent window's dom), instead of on iframe's window

unable to take screenshot of mouseover in selenium -

Image
i trying take screenshot of sub menu happens on hovering in selenium using takesscreenshot . not working. screenshot taken sub menu not present in image. have tried using implicit wait after hover, nothing worked. please suggest method capture screenshot of sub menu. contactus.hoverhm(); screenshot = ((takesscreenshot) pagefactorybase.getsharedwebdriver()).getscreenshotas(outputtype.bytes); scenario.embed(screenshot, "image/png"); this did trick me. pretty sure work you. _driver = new firefoxdriver(); _driver.navigate().gotourl("http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseover_mouseout"); _driver.switchto().frame(_driver.findelement(by.id("iframeresult"))); actions builder = new actions(_driver); builder.movetoelement(_driver.findelement(by.tagname("p"))).build().perform(); var screenshot = ((itakesscreenshot)_driver).getscreenshot

xaml - Show one of multiple items on the page (tab-like interface) -

i want have tab-like interface have multiple buttons (tabs) , when user press 1 of button show corresponding container , hide other ones. something like: <!-- buttons --> <stackpanel verticalalignment="stretch" grid.column="0"> <button style="{staticresource detailsectionbutton}" content="info" click="button_click"/> <button style="{staticresource detailsectionbutton}" content="map" click="button_click2"/> <button style="{staticresource detailsectionbutton}" content="attachment" click="button_click3"/> </stackpanel> <!-- info --> <scrollviewer x:name="secinfo" grid.column="1" visibility="collapsed" ... <!-- map --> <map:mapcontrol zoomlevel="6" x:name="secmap" gri

SAS: Summing across rows conditional on date in each row -

i have information shown in first 4 columns in table below , add column calls_previous_3_days containing sum of calls each custid each area previous 3 dates. i.e., if custumer made call support on 17jan2015 new variable show sum of number of calls customer made support during period 14jan2015-16jan2015. how calculate sum in column calls_previous_3_days dependent on custid, area , date? custid area date calls calls_previous_3_days 3137 support 05jan2015 1 0 3137 support 14jan2015 4 0 3137 support 16jan2015 1 4 3137 support 17jan2015 1 5 3137 support 20jan2015 2 1 3137 support 22jan2015 1 2 5225 support 26jan2015 1 0 5225 support 27jan2015 1 1 5225 support 28jan2015 1 2 5225 sales 14feb2015 1 0 5225 sales 15feb2015 1 1 5225 sales 22feb2015 1 0 you can achieve arrays, storing last 3 values , dates , summing dates

javascript - Ajax return not show on page source Codeigniter -

i have problem ajax return values. returned data not showing on page's source code. this controller code in codeigniter: public function get_rooms(){ $rooms_selected = $this->input->get('q', true); $this->load->model('roomreservation_model'); $room_numbers = $this->roomreservation_model->numberofroom($rooms_selected); echo '<select class="form-control" name="room_number" id="room_number">'; foreach ($room_numbers $value) { echo '<option value="'.$value->room_number.'">'.$value->room_number.'</option>'; } echo '</select>'; } html code <div class="col-lg-12"> <h2 class="sub-header">room detail</h2> <div class="col-lg-6 col-xs-12 form-label"> <label for="room type">room type</label> <select cla

python - Print the current footprint of arbitrary objects -

i looking way print out current state of object. i want include variables declared using self (note: not want see methods, or other information on object). using this: def __str__(self): return str(', '.join("%s: %s" % (str(s), str(self.__dict__.get(s))) s in self.__dict__)) in words: i loop on object's __dict__ for each value, create tuple consists of str(key) , str(value) the resulting tuple joined in string of following format: "key:value, key:value, ..." my question is, there more convenient way? obviously, uses __str__ method , may want change behavior serve purpose.

stderr output when using popen in C++ linux -

when use simple program standard output of process, somehow standard error of process, although man page popen says standard output redirected. possible related shell used when forking process popen ? errer simple program outputting stderr ( cerr << "hello"; ). i'm using rhel 6.4. thanks! #include <iostream> #include <cstdio> using namespace std; int main () { file *fd = popen("errwr", "r"); char str [1024]; while (fgets(str, 1024, fd)) { cout<<str<<endl; } return 0; } you're not getting output stderr in program using popen . following simple example shows, error stream started application printed in terminal, without being read in program. popen redirects stdout stream , stderr stream not affected, it's printed terminal. #include <iostream> #include <cstdio> using namespace std; int main () { file *fd = popen("errwr", "r&q

if statement when environment variable exists/not exists in batch files -

i want check if environment variable set in pc. if yes x if not y. i tried these , variations of them: if exists %sign% runtest.exe --redirect -l %name% else runtest.exe -l %name% if "%sign%" == "" runtest.exe --redirect -l %name% else runtest.exe -l %name% none of them work in both cases (when environment variable sign exists , when doesn't exist).sometimes in 1 case... please can help? thanks! if conditionally perform command if defined sign ( runtest.exe --redirect -l %name% ) else ( runtest.exe -l %name% ) or shortly if defined sign (runtest.exe --redirect -l %name%) else (runtest.exe -l %name%) valid syntax: all ) , else , ( must on line follows: ) else ( note : if defined return true if variable contains value (even if value space). according above predicate, if defined sign condition seems equivalent reformulated test if not "%sign%"=="" valid in batch only , %undefined_vari

android - Select and place different shapes in canvas using OnTouch event -

i new android programming in project layout, need created color palette in grid layout(i put buttons , set color background). shapes(triangle,square , circle buttons well) in linear layout next these 2 relative layout users can draw shapes when user touch on 1 of shape , touch on relative layout (which next shapes), particular shape should drawn , colors. example if user touch on circle shape, touch on screen, circle should drawn @ point user touched. i managed create 2 touch events in 2 different classes, i.e 1 selecting shapes , other placing shapes in layout. i have no idea how combine 2 classes together. can please give me idea how should approach project. should create shapes (should create separate classes each shape/in ondraw() )? if create shapes in ondraw() how can call in ontouch() ? any great. in advance. i hope explained properly, sorry not in english , first time posting in forum. generally draw shapes on canvas touch event, used code below,

c# - WPF Maximized Window bigger than screen -

when creating wpf window allowstransparency="true" windowstyle="none" , maximizing via this.windowstate = windowstate.maximized; window gets bigger screen. when setting allowtransparency="false" have border around window, window won't bigger screen. in case have 1920x1080 screen , window becomes 1934x1094. on 1280x1024 screen window become 1294x1038. window become still big this, whether or not allowtransparency enabled or not, yet disabled works properly. setting allowtransparency before maximizing doesen't work , throws invalidoperationexception. how wpf window without windows-style border, yet maximize properly? it seems pretty common issue. appears you'll have bind height , width actual height/width of screen stated in stackoverflow post: borderless window application takes more space screen resolution . i hope solves issue you're facing.

c# - Dynamic IVR menu application in MVC using twilio API -

i trying develop application in mvc4 client can configure dynamic menu incoming calls user interface using twilio api. there opensource project exist or voice model dynamic ivr menu can idea , application flow gui design. in regard highly appreciated. twilio developer evangelist here. to knowledge there isn't .net project demonstrates how build ivr using twilio. however, there few tutorials showing how it, , because of uses twiml, should able generate using libraries, or making requests return such verbs when necessary. i stat off looking @ following: project: build simple ivr example in php, should able translate c# ivr: basics resource tells how ivr's work build ivr system twilio , django tutorial showing how build ivr using django with urls above should ale ivr , running in no time, means feel free reach out me if need help. i'm c# developer myself, able assist if stuck anything.

advanced custom fields - How can I restrict Two dates in ACF date picker for Starting date and Ending Date in Wordpress? -

i have created event post type in wordpress. have put starting date , ending date acf datepicker. i want admin can select ending date greater starting date. is there way restricting starting date , ending date? for example, if admin choose 1st jan 2016 starting date, can select ending date 1st jan or greater selected date. i think can java script , use code set limit of end date : $( ".selector" ).datepicker({ mindate: new date( ) });

javascript - AJAX jquery json sending array to php -

i'm trying send associative array via ajax $.post php. here's code: var request = { action: "add", requestor: req_id, ... } var reqdetails = $("#request_details").val(); switch(reqdetails){ case 1: request[note] = $("#note").val(); break; ... } if(oldrequest()){ request[previousid] = $("old_id").val(); } $('#req_button').toggleclass('active'); $.post("scripts/add_request.php", { request_arr: json.stringify(request) }, function(data){ console.log(data); $('#req_button').toggleclass('active'); }, 'json'); and i'm trying read received data in php script: echo json_decode($_post["request_arr"]); but it's not working. i'm newbie js, can't figure out i'm doing wrong. check below link reference

android - Gradle: How to execute task after create lib.aar file? -

i have gradle task unbacks lib-debug.aar need execute task after crate lib-debug.aar file task unzip<<{ copy { def aarfile = file("${builddir}/outputs/aar/lib-debug.aar") def outputdir = file("${builddir}/outputs/eclipse") ziptree(aarfile) outputdir } you can do: unzip.dependson assemble that make whenever run unzip task, assemble task has have run before.

postgresql - Comparing orientations with Postgres/PostGIS -

i'm working on app need take orientation of user's phone (e.g. using web orientation api or otherwise), , compare stored orientation. need determine if these orientations close enough each other in terms of degrees. edit: end goal of tell when user facing in exact same direction stored in database (i.e. tilt isn't important) so conceptually we're finding distance between 2 points on circle, these points determined 2 angles, alpha , beta, rather latitude , longitude, they're both out of 360 degrees (like this question suppose). web api returns 3 different angles alpha, beta , gamma, explained here , care alpha , beta think. firstly, how store 3d orientation in postgres? model data point latitude , longitude, annoying have convert angle out of 360 angle out of 180 or 90). there better format store orientation in postgres? secondly, how compare orientations? i've found function, st_distance_spheroid , compares distance between points on sphere in ter

c# - How to perform background task without blocking the GUI but transfer back information to main thread? -

i following: have button , table on gui. when press button, task started this task while loop, giving me data on each iteration how can run loop , obtain data each iteration of in main gui table, without blocking gui? important, because while stop condition again button on gui. i have tried using backgroundworker , cannot figure out how send data @ every loop iteration (???) can result @ end, not target. if launch worker in loop (but not have loop in worker), not work. private void continuouscoordinateaquisition(object sender, doworkeventargs e) { while (continuouspositionaquisitionflag == true) // while monitoring not stopped, positions { // xyzwpr world coordinates robotcoordinatesxyzwprworld xyzwprworld = robi.getrobotposition_xyzwpr_world(); something........... retuns values need in gui // sleep defined time system.threading.thread.sleep(1000); // wait } } the calling be backgroundw

ios - Core Data and unix timestamp date -

i have core data user locations: longitude,latitude etc. and try list of available days: nsmanagedobjectcontext *context = [self managedobjectcontext]; nsfetchrequest * request = [[nsfetchrequest alloc]init]; [request setentity:[nsentitydescription entityforname:@"locations" inmanagedobjectcontext:context]]; nspredicate *predicate = [nspredicate predicatewithformat:@"device_id == %@", deviceid]; [request setpredicate:predicate]; nssortdescriptor *sortdescriptor = [nssortdescriptor sortdescriptorwithkey:@"created_at" ascending:no]; [request setsortdescriptors:[nsarray arraywithobject:sortdescriptor]]; request.returnsdistinctresults = yes; [request setpropertiestofetch:@[@"created_at"]]; [request setresulttype:nsdictionaryresulttype]; nsarray *results = [context executefetchrequest:request error:null]; nsmutablearray *datearray = [[nsmutablearray alloc]init]; nsdateformatter *formatter= [[nsdateformatter alloc] init]; for(nsdict

html - Javascript:: Play multiple audio files via HTML5 Audio Player playlist -

i'm working on code play html5 audio file(s). let start code first easier explain. here code : <style> .btn { background:#fff; border-radius:5px; border:1px solid #000; height:25px; width:25px } .play:after { content:">" } .pause:after { content:"||" } </style> <button class="btn play" id=hezigangina-gravity></button> <button class="btn play" id=hezigangina-pug></button> <script> ibtn=document.getelementsbytagname('button'); for(j=0;j<ibtn.length;j++) { ibtn[j].addeventlistener ( 'click', function() { var audio=new audio(this.id+'.mp3'); if(audio.pause) { audio.play(); ibtn[j].classlist.remove("play"); ibtn[j].classlist.add("pause"); } else {

javascript - How To Active Bootstrap Tab after Button Click in ASP.NET -

i working in asp.net , use twitter bootstrap plugins. in form use tab. there 2 option in tab. #1 map , #2 address . submit form , save data database when data save want saved data shown in #2 tab ( address tab ). found many article in stackoverflow related it, not achieve this. code:-asp <div class="map-panel"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#divmap">map</a></li> <li><a data-toggle="tab" href="#divaddress">address</a></li> </ul> <div class="tab-content"> <div id="divmap" class="tab-pane fade in active"> <div id="geomap" style="width: 100%; height: 450px;"> <p>

javascript - Get element node count with jquery -

i don't know if can explain right... i have table this: <table> <tr> <td class="mytd">aaa</td> <td class="mytd">bbb</td> <td class="mytd">ccc</td> <td class="mytd">ddd</td> <td class="mytd">eee</td> </tr> </table> some jquery this: $('.mytd').on('click', function(e){ //... here ...// }); when click on td want node count of clicked td. e.g. if click on ccc want alert 3 is possible in way or have explizit add id ? $('.mytd').on('click', function(){ alert( $(this).index() ); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="mytd">aaa</td> <td class="mytd">bbb</td>

hive - How to directly get input tables' statistics in HQL? -

this page statsdev - apache hive - apache software foundation tells following statistics once input tables & partitions information in hive: number of rows number of files size in bytes however, can statistics through unparsed hql directly? or them after parsing input tables & partitions information hql? keyword explain want: languagemanual explain - apache hive - apache software foundation

php - is there any way we can post image on facebook using facebook app on access allowed user's wall on be half them/app endless? -

is there way can post image on facebook using facebook app on access allowed user's wall on half them/app ? we have access of user 1 time , whatever user upload automatically post post wall. we have tried storing user access token expire after 2 months. so if there option generate no expire token, work. as figured out, long-lived access token expire after 60 days, should more enough use cases. in case, posting user's timeline after they take action (and consent) should work fine need request new token. , if use javascript sdk, done in background. more here .

mysql - Big Query with Python -

is there anyway run queries repeatedly on google big query using python script? i want query dataset using google big query platform weeks data , want on year. bit tedious query dataset 52 times. instead prefer write python script(as know python). i hope point me in right direction regarding this. bigquery supplies client libraries several languages -- see https://cloud.google.com/bigquery/client-libraries -- , in particular python, docs @ https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/?_ga=1.176926572.834714677.1415848949 (you'll need follow hyperlinks understand docs). https://cloud.google.com/bigquery/bigquery-api-quickstart gives example of command-line program, in either java or python, uses google bigquery api run query on 1 of available sample datasets , display result. after imports, , setting few constants, python script boils down to storage = storage('bigquery_credentials.dat') credential

android - Container, Image and Text: How to get it working together? -

well, have container, image , texts (inside container), way: <relativelayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5dp" android:layout_margin="10dp" android:id="@+id/btn"> <imageview android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/background" android:src="@drawable/background" android:scaletype="centercrop"/> <linearlayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <imageview android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon_left" android:layout_gravity

javascript - Server-Sent Events with Ruby Grape -

i trying create server-sent events on ruby grape api . problem connection seems closed fast time, connection closed event time on test webpage. the client connects server can see method being called, know why connection not constant , why don't receive data send using thread. here ruby code: $connections = [] class eventsapi < sinantra::base def connections $connections end "/" content_type "text/event-stream" stream(:keep_open) { |out| puts "new connection" out << "data: {}\n\n" connections << out } end post "/" data = "data\n\n" connections.each { |out| out << data } puts "sent\n" end end here javascript: var source = new eventsource('http://localhost:9292/events'); source.onmessage = function(e) { console.log("new message: ", e.data); showmessage(e.data); }; source.onopen =

internet explorer - How to prevent SVG elements from gaining focus with tabs in IE11? -

there inline svg element among html form elements. when navigate through elements tab key, svg focused, in ie11 only, if svg element has tabindex="-1" attribute set every elements inside it: <svg width="20px" height="20px" tabindex="-1"> <g tabindex="-1"> <circle cx="8.5" cy="8.5" r="7.75" stroke="#999" stroke-width="1" tabindex="-1" /> […] </g> </svg> to sure it's focusing on element, call document.activeelement in console, , yes, prints out svg thing. internet explorer 11 should honor negative value, other dom elements, or not? can possibly prevent this? in case missed it, answer commented: tabindex part of upcoming svg2 , not yet supported ie11. have @ this question work-around. thanks @altocumulus

android - setSupportActionBar() throws Nullpointer exception -

i new android , following following tutorial material design toolbar : http://www.android4devs.com/2014/12/how-to-make-material-design-app.html but after implementation of code. following error shown in logcat : 04-01 19:16:10.214 2246-2253/com.example.bhaskar.ddit_results e/art﹕ failed sending reply debugger: broken pipe 04-01 19:16:11.985 2246-2246/com.example.bhaskar.ddit_results e/androidruntime﹕ fatal exception: main process: com.example.bhaskar.ddit_results, pid: 2246 java.lang.runtimeexception: unable start activity componentinfo{com.example.bhaskar.ddit_results/com.example.bhaskar.ddit_results.mainactivity}: java.lang.nullpointerexception: attempt invoke virtual method 'java.lang.charsequence android.support.v7.widget.toolbar.gettitle()' on null object reference @ android.app.activitythread.performlaunchactivity(activitythread.java:2298) @ android.app.activitythread.handlelaunchactivity(activitythread.java:2360) @ android.app.acti

objective c - subview user interaction disabled on UIViewController on iOS 7 -

i have .xib file in app. inserted .xib file subview viewcontroller. have user interaction enabled, , on ios 8 works expected when run app on ios 7 user interaction not working. check in attribute inspector, user interaction enabled checked or not.

Python Object with @property's to dict -

i'm new python please excuse if i've glazed on simple this. i have object this: class myobject(object): def __init__(self): self.attr1 = none self.attr2 = none @property def prop1(self): return foo.some_func(self.attr1) and instantiate this: a = myobject() a.attr1 = 'apple' a.attr2 = 'banana' and method it's wrapped in expects return of dict, this: return a.__dict__ but prop1 not included in return. understand why is, it's not in object's __dict__ because holds real attributes. so question is, how can make return, return this: {'attr1': 'apple', 'attr2': 'banana', 'prop1': 'modifiedapple'} other right before return doing: a.prop1_1 = a.prop1 you should leave __dict__ be, use attributes live directly on instance. if need produce dictionary attribute names , values includes property, add property or method produces new dicitonary

Make SQL Server database read only except for one stored procedure -

i have stored procedure migrate data database another. exclude error, want make database read every transaction except mine. use sqlconnection , sqlcommand run script. there way this? set database single-user mode . when put in single-user mode, have connection available. long don't relinquish connection, no 1 else can connect. be warned, close existing connections other users. prevent other connections being made. more information: https://msdn.microsoft.com/en-us/library/ms345598.aspx

c# - Why won't JsonConvert deserialize this object? -

i have json: { "cutcenterid":1, "name":"demo cut center", "description":"test", "isavailable":true, "e2customerid":"110000", "numberofmachines":2, "machines":[] } i have following poco: public class cutcenter { int cutcenterid { get; set; } string name { get; set; } string description { get; set; } bool isavailable { get; set; } string e2customerid { get; set; } int numberofmachines { get; set; } } i try following line of code json set above json , _cutcenter member variable. _cutcenter = jsonconvert.deserializeobject<cutcenter>(json); after _cutcenter set defaults. why? doing wrong? your members private. try this. public class cutcenter { public int cutcenterid { get; set; } public string name { get; set; } public string description { get; set; } public bool isavailable { get; set;

ajax - Separating PHP session variables into their own files -

i thinking writing session handler (using session_set_save_handler) stores each session variable in it's own file. maybe have session_id directory, , each variable stored in own file, session key filename. my purpose is: non-blocking (or lesser-blocking) session. i.e. when run script opens session, don't have close session before script can write session. thinking session handler can open , close single file write access (read access ok because can close session , still access values using $_session). write given session variable, script won't need lock entire session. the application quite database heavy (it's central database biology research lab) hence why don't want put load on database storing user's sessions in database (although alternative, maybe set additional database sessions?). sessions used fair bit user's form inputs saved session using ajax (on change, persistence) , there can multiple instances of given form. facilliate garbage col

php - Getting a decimal qty from subtracting two times -

how subtract 2 time variables each other answer decimal number? time variables this: 07:32:00 i looking this: $total = $start_time - $end_time echo "$time hours"; output this: 5.3 hours you cant subtract on strings. variable "07:32:00" string. you have convert time unix timestamp php function strtotime . and aslo have subtract largest time. here solution: echo (strtotime("15:00:00") - strtotime("11:30:00"))/(60*60);

java - Operation Time Out Error in cqlsh console of cassandra -

i have 3 nodes cassandra cluster , have created 1 table has more 2,000,000 rows. when execute ( select count(*) userdetails ) query in cqlsh, got error: operationtimedout: errors={}, last_host=192.168.1.2 when run count function less row or limit 50,000 works fine. count(*) pages through data. select count(*) userdetails without limit expected timeout many rows. details here: http://planetcassandra.org/blog/counting-key-in-cassandra/ you may want consider maintaining count yourself, using spark, or if want ball park number can grab jmx. to grab jmx can little tricky depending on data model. number of partitions grab org.apache.cassandra.metrics:type=columnfamily,keyspace={{keyspace}},scope={{table​}},name=estimatedcolumncounthistogram mbean , sum 90 values (this nodetool cfstats outputs). give number exist in sstables make more accurate can flush or try estimate number in memtables memtablecolumnscount mbean

What happens when there is a javascript runtime error? -

i understand causes runtime errors. want understand how browser behaves afterwards. will event handlers attached before error still work? if script loaded async finishes after runtime error able execute? basically, how catastrophic run-time error? an uncatched runtime error stops current execution, may be the execution of script the call of event handler suppose have runtime error while handling event, problem might have (apart not handling event) non consistent state of user variables if event handler modifies of them. other event handlers won't impacted besides that. so can considered non catastrophic (i guess don't have remember it's practice fix errors anyways , flooding console errors isn't thing).

asp.net web api - Inject Default value for Web-Api Method parameter when its null -

i have web api method like; [httpget, route("users")] public httpresponsemessage getusers([fromuri] usersearchdto searchparams) {} the searchparams optional parameter when pass no search values , use http://api-uri/users becomes null , have add check in body of method avoid null reference exception. is there way using actionfilters or else inject default value parameter of web api method avoid if (searchparams == null){ searchparams = new usersearchdto () } not know of. honestly, you're doing pretty it. if want make bit neater, yo can condense null check 1 line so: searchparams = searchparams ?? new userseachdto();

java - JTextfield UML Class Diagram -

i'm having 2 classes specific purpose in project, doing putting related gui in let's class 1 , functionality , data manipulations in class 2. class 2 contain member variables such int, string represented on class diagram. class 1, have member variables of type jtextfield, jcombobox, among others used in gui. my question : show member variables such jtextfield on class diagram? do show member variables such jtextfield on class diagram? no only variables need mentioned in class diagram. for specifications of variable, create 1 more file (known uispecification) , there mention type of variable like variable type str text usually uispecification file made in xl sheet

distributed computing - Run multiple instance of a process on a number of servers -

i run multiple instances of randomized algorithm. performance reason, i'd distribute tasks on several machines. typically, run program follows: ./main < input.txt > output.txt and takes 30 minutes return solution. i run many instances of possible, , ideally not change code of program. questions are: 1 - online services offer computing resources suit need? 2 - practically, how should launch remotely processes, notified of termination, , aggregate results (basically, pick best solution). there simple framework use or should ssh-based scripting? 1 - online services offer computing resources suit need? amazon ec2. 2 - practically, how should launch remotely processes, notified of termination, , aggregate results (basically, pick best solution). there simple framework use or should ssh-based scripting? amazon ec2 has api launching virtual machines. once they're launched, can indeed use ssh control jobs, , recommend solution. expect other

Results from getimagesize (width and height) aren't correct in PHP -

i got problem getimagesize() . occurs when upload image but.. sometimes. the script should check image size avatar (profile-pic). if lower or equals 200px x 200px it's ok. i'm not done script yet, security things missing. i'm totally confused why happens , why happens. my script: //updateavatar if(isset($_files['uploadavatar']) , (isset($_session['user']) or isset($_session['dev']))) { //upload $uploaddir = "../img/avatar/";//relative path (we're in php folder [one step img]) $avatarextension = pathinfo($_files['uploadavatar']['name'], pathinfo_extension);//avatar extension (jpg,png,gif) if($avatarextension == "gif" || $avatarextension == "jpeg" || $avatarextension == "jpg" || $avatarextension == "png") { $_files['uploadavatar']['name'] = $loginname."_avatar".".".$avatarextension;//build new name (max 4 differe

How to not show Visual Studio 2013 floating doc icons in taskbar? -

i using vs 2013 express, desktop. regularly tear off doc tabs , put doc on other monitor. adds icon windows taskbar each floating doc. how stop that? wasteful of space not "combine" icons on taskbar (and never will). thanks actually windows behavior rather vs-specific behavior , can see in other applications (e.g. google chrome, error pop-ups in apps, etc.) , has simple rationale behind allow user switch between application windows. makes lot of sense otherwise you'll have mess many windows in order unhide window you'd work with. i'm unaware of way change behavior of windows , per above tend believe intentionally not possible.

php - Extract sub array resulting key=id and value=name in CakePHP -

i have nested array: array ( [id] => 1 [name] => group 1 [0] => array ( [id] => 1 [name] => group 1 ) [1] => array ( [id] => 2 [name] => group 2 ) [2] => array ( [id] => 7 [name] => group 7 ) ) and extract sub arrays [0] , [1] , , [2] in 1 single array following format: array( [id] => [name] ) in other words have result: array ( [1] => group 1 [2] => group 2 [7] => group 7 ) *note: tried set::classicextract($my_array['group'], '{n}.name'); can't figure out how group.id key array. guidance appreciated. this should work you: (here first array_filter() values out, don't have numeric key. after array_combine() id column name column array_column() ) <?php $result = array_filter($arr, function($k){ return is_numeric($k);

java - multiple properties in spring. property in PropertyPlaceholderConfigurer class -

i'm trying create spring project. goal build project jar , war in future. use abc.properties file in classpath contains "conf.path.dir" property. war , jar projects use configuration different locations. , i'm replace abc.properties @ build time , use configure propertyplaceholderconfigurer bean. <bean id="first" class="org.springframework.beans.factory.config.propertyplaceholderconfigurer" autowire-candidate="false"> <property name="ignoreunresolvableplaceholders" value="true"/> <property name="locations"> <list> <value>classpath:abc.properties</value> </list> </property> </bean> <bean id="second" class="org.springframework.beans.factory.config.propertyplaceholderconfigurer" depends-on="first"> <property name="ignoreunresolvableplaceholders" value=&q

ruby on rails - Eager load associations in nested set model -

i'm using nested set represent nested comments (1 discussion has many comments, comments can replied to) , (if possible) eager load answers comments. at moment load root nodes , iterate on them, if have descendants render them. however, if there lot of root nodes answers, triggers lot of db requests. a comment has these columns: rgt, lft, parent_id i tried create relationship this: class comment < activerecord::base has_many :answers, -> (node) { where("lft > ? , rgt < ?", node.lft, node.rgt) }, class_name: "comment", foreign_key: :parent_id end this fetches answers comment when called on comment instance. however, if try eager_load ( discussion.comments.includes(:answers) ) blows since node nil. is possible eager load this? i think, i've found solution. if see right, data model looks this: discussion ---------- ... comment ---------- discussion_id:int parent_id:int lft:int rgt:int then ar model classes be: cla

python - access a file with a specific link in django -

in django, have file foo.txt in static folder, can accessed through www.example.com/static/foo.txt. how possible access file simple doing www.example.com/foo.txt? (without redirections) thanks in advance! i think selcuk right, save file on server directories, or static files, simple point url there <a href="/static/files/foo.txt">foo text file</a> watch file permissions though

asp.net - ASP Chart Control - issue displaying all SQL data -

i new @ using mschart control. know how single series of data display in column chart, having issues displaying multiple data values in chart. here data sql query need display: area totalcnt compliant cpercent noncompliant ncpercent area1 29027 25468 87.7 3559 12.3 area2 13659 12035 88.1 1624 11.9 area3 25358 22221 87.6 3137 12.4 area4 47747 42340 88.7 5407 11.3 here's series section of column chart: <series> <asp:series isvalueshownaslabel="true" chartarea="chartarea1" label="#valy" name="compliant" bordercolor="180, 26, 59, 105" color="#00cc00" xvaluemember="area" yvaluemembers="compliant"></asp:series> <asp:series isvalueshownaslabel="true" chartarea="chartarea1" label="#valy" name="non-compl

user defined types - SQL Azure Create Rule walkaround to use UserDefinedDataType -

create rule not supported on sql azure. there walkaround ? create rule [dbo].[rule1] @variable not null i wanna use userdefineddatatype supported in azure, create strong type email type, percentage type , on. without rules it's useless... solution ? thanks user-defined rules not supported on v1 servers. however, if upgrade server latest sql database v12 update create rule & many other sql server features available. see links below: http://azure.microsoft.com/en-us/documentation/articles/sql-database-preview-whats-new/ http://azure.microsoft.com/en-us/documentation/articles/sql-database-preview-upgrade/

Resize an image dynamically with CSS inside a table-cell div -

i trying create 2 columns of equal width, left 1 containing text , right 1 containing image. image resize down width of column if image width greater column width, image keep original size if image less column width. have tried instructions in this question , image, if larger, consume whatever space needs, squishing column on left containing text. wondering if has how "table-cell" divs behave, or if precedence issue browser accommodate image before text. code looks this: <div style="display: table; width:100%;"> <div style="display: table-row;"> <div style="display: table-cell; width: 50%; vertical-align: middle;"> <h1>header</h1> <p>description</p> </div> <div style="display: table-cell; width: 50%; vertical-align: middle;"> <img style="max-width: 100%;height:auto;" src="image.jpg">

twitter bootstrap - Boostrap CDN with 16-columns instead of 12 -

i want use latest bootstrap cdn, defaults 12 column layout. way customize 16 col layout download , host files yourself? edit: i'm asking how bootstrap through cdn. use bootstrap cdn https://cdnjs.com/ , works great, except 12-col layout. there 2 options this. you override bootstraps grid system own css file. <link rel="stylesheet" href="/cdn/path/to/bootstrap.css" /> <link rel="stylesheet" href="/my/path/overide_bootstrap.css" /> this can tedious task , not recommend doing way. customize bootstrap , use own version if go http://getbootstrap.com/customize/ can customize , download customized version of bootstrap. looking located @ http://getbootstrap.com/customize/#grid-system . once has been downloaded have few options: serve files own project. use free cdn service there multiple cdn services can use, such cloudflare ( https://www.cloudflare.com/features-cdn ) or can use cdnjs ( https://github.

python - Why can't I access more than 25 tweets using tweepy search API? -

i'm using tweepy in python search tweets. i'm using tweepy.api.search() query older tweets, , noticed can't access 500 tweets @ once. in fact, can't return more 25. i have used both count , rpp (results per page) keywords. can't seem figure out if i'm not allowed access many tweets @ once, or if buggy. here code: for tweet in api.search(q='obama', count=500, show_user=false, rpp=500, geocode='38.899722,-77.048363,500mi'): print tweet.created_at, '\n', tweet.text, '\n\n' this gives me 25 tweets output. here first few show it's working: 2015-04-01 16:42:28 "@jonahmarais: me , michelle obama dating guys" lot twist. april fools day. 2015-04-01 16:42:05 "@jonahmarais: me , michelle obama dating guys" sike. 2015-04-01 16:38:44 forget #winstonchurchill #obama isn't measuring #nevillechamberlain says http://t.co/6jzqxjudrh #irantalks #israel

javascript - magnific-popup generates "file not found" error for YouTube videos -

i trying make popup containing youtube video. code have $(document).ready(function() { $('#vid1').magnificpopup({ items:{ src: 'http://www.youtube.com/watch?v=0o2ah4xlbto' }, type:'iframe' }); }); i popup says the file or directory not found. missing or doing wrong? have tried multiple types of youtube links; result in same error. are trying view video local file? youtube player blocks that. (file:///) have test videos web server. (http(s)://)

Internet Explorer Caching File Uploads? -

Image
i have basic page includes <input type="file"> element. when submit form file selected, server responds spreadsheet gets opened in excel (a "new window"). implication of behavior initial screen , input element still visible in ie. if change data on disk of selected file , resubmit form, internet explorer uploads old contents second time; latest changes not present in content sent server. if select file via input's browse... button again, new file contents uploaded expected. firefox sends file's contents disk expected/desired behavior. seems internet explorer doing kind of caching of uploaded file contents. is there way disable "feature" , have ie pull data disk each time form submitted? is there documentation available on behavior? it's first time i've encountered , searches have largely come empty. you can test out conjecture live demos posted on ms-connect . [...] bug began ie10, when filelist , blob imple

javascript - How to get "computed" text content of an HTML node (whitespace adjusted) -

Image
i want able "computed" text content of html node, i.e. rendered browser. example : consider following html: <html> <body> <p>a b c d e f &nbsp; g <div>1</div><div>2</div> <a>3</a><a>4</a> <button onclick="javascript:alert(document.body.textcontent)">click me</button> </p> <pre>h i</pre> </body> </html> here's picture of how above html renders in chrome 41.0.2272.101 m on windows 7: is there simple, or relatively simple, way approximate text of <body> node, example, in way captures fact html node boundaries "generate" whitespace (like boundary between <div> nodes in above example)? i approximation of text of <body> node string like: a b c d e f g 1 2 34 click me h