Posts

Showing posts from August, 2015

php - Get last part of a string preceded by a forward slash -

i have following viemo url: http://player.vimeo.com/video/5836196 how able last part of url 5836196 using php? you can use substr / strrpos - substr( $url, strrpos( $url, '/' )+1 ); demo

excel - Macro exiting early with no error -

i using below code copy in workbooks particular folder 1 workbook. 9 out of 10 times code works fine , data copied macro appears exit without finishing msgbox never displays , not error message. macro appears have been exited allows me run other macros. can advise me might causing this? seems happen if start other things on computer while macro running. sub getsheets() application.screenupdating = false dim response response = msgbox("this take time run. sure want proceed?", vbyesno) if response = vbno exit sub end if application.run ("getxlsxfiles") application.run ("getxlsfiles") datacopied = 1 sheets("instructions").select msgbox "completed successfully" end sub sub getxlsxfiles() dim sheet worksheet path = sheets("instructions").range("filename").value filename = dir(path & "*.xlsx") while filename <> "" workbooks.open filename:=path & filename, readonly:=true,...

javascript - Type casting when == used instead of === -

this question has answer here: which equals operator (== vs ===) should used in javascript comparisons? 48 answers i don't prefer using == today experimenting following code including == , results bit confusing me. can please explain happening? all these falsy values: '', 0, false, undefined, null suppose did: if (undefined == null) { alert('a'); } else { alert('b'); } the statements below give true : null == undefined 0 == '' false == '' 0 == false but why code below return false ? undefined == 0 undefined == '' null == 0 because 0 , false , '' "values" while null "absence of value" , undefined "absence of definition". thus, can compare "values" each other, same "non-values". can't compare "values" "n...

heroku - Where to host Meteor-Apps? -

i want build meteor-app run little side-project/business. in mind: i want cheap environment (online) test , share progress i want have option scale in terms of production in few months i want use standard command line tools push service the database options have scale if need more i've started looking heroku , there "good practices" can recommend? never hosted meteor-app, , i want avoid private server because of administration etc. meteor apps ready deploy heroku. question broad, heroku fits bill every parameter specified. here's flow creating example meteor app , deploying it: $ meteor create --example leaderboard $ cd leaderboard $ git init . && git add . $ git commit -m "first commit" $ heroku create --buildpack https://github.com/jordansissel/heroku-buildpack-meteor $ git push heroku master

How can I configure my index to use BM25 in ElasticSearch using the JAVA API? -

i'm trying migrate mysql database elasticsearch can use full-text search technique using bm25 similarity on each fields. i'm using java fetch entries mysql , add them elasticsearch index. i'm building index using java index api , can't figure out way set bm25 similarity on fields. i consider table products table mysql , dev index products it's index type. the original table products contains following fields : id title description you can find code on github , if you'd take look. it's forked project i've configured maven integration. any suggestion , welcome, thanks! i found answer question. here code : settings settings = immutablesettings .settingsbuilder() .put("cluster.name", "es_cluster_name")) // define similarity module settings .put("similarity.custom.type", "bm25") .put("similarity.custom.k1", 2.0f) ...

php - SQL-ASCII encoding in database throws Error: json_encode(): Invalid UTF-8 sequence in argument -

i have old postgresql database sql-ascii encoding.. in laravel, tried query records containing characters Ñ , ñ unfortunately, throws error json_encode(): invalid utf-8 sequence in argument . how solve problem? please help.

jquery - Counting and storing the number of checkboxes in a sharepoint list -

i have sharepoint list that's purpose measure competency of team. have highly regulated financial environment , there on 790 "core competencies" maintain on 200 colleagues. i've decided use sp 2013 solution. list contains fields "credit cards" "multi choice check box fields" inside credit cards - there more 30 checkboxes (eg. opening credit card , closing credit card, refunding fee, etc) essentially, when users select boxes (basically saying "i know how this") , i'd number of checkboxes in field counted , placed in sp field. example, checkbox field called "credit cards" there field called creditcardscore counts number of boxes ticked in credit card score , total number , displays %. (we can split multiple fields, needs update every time form opened) so if user ticked 15 out of 30 boxes, i'd know they're 50% competent @ job. (so can focus on getting them trained up) i'd use jquery i've seen numero...

scheme - Why are pattern variables also renamed in macro expansion? -

while reading dybvig's paper syntactic abstraction in scheme , noticed algorithm renames pattern variables. means pattern variables may cause capture. have no idea in case cause capture? can enlighten me? a macro can expand macro definition using patterns. pattern variables have lexical scope normal variables, need renamed too. example of macro expanding macro definition. #lang racket (define-syntax (define-get/put-id stx) (syntax-case stx () [(_ id put!) #'(define-syntax id (syntax-id-rules (set!) [(set! id e) (put! e)] [(id (... ...)) ((get) (... ...))] [id (get)]))])) (define id 0) (set! id 42) (define-get/put-id clock (λ() (displayln "reading clock") id) (λ(x) (displayln "setting clock") (set! id x) id)) clock (set! clock 10) clock ;;; output reading clock 42 setting clock 10 reading clock 10

angularjs - implement a new directive already compiled template -

as know, compilation passes once , not repeat. if have controller example <div ng-controller="somecontr"></div> , create <span>{{ text }}</span> in controller, , put there item using appendchild () method, or realties <div ng-controller="somecontr"> <span>{{ text }}</span> </div> question, how can make work expression {{ text}} first , 1 of important things understand: don't manipulate dom in controllers, put dom manipulation staff directives , let controllers care of model (scope). in order add dom elements dynamically in directive can use $compile service (see usage section) same job if put string part of template: html <div app-directive ng-init="text = 'hello world'"></div> javascript angular.module('app',[]). directive('appdirective', function($compile) { return { link: function(scope, element) { var html = ...

python - Difference between not dict and not dict=={} -

came in today , debugged find there deviation in behaviour predicted result of not adict being treated differently not adict=={} . in know highlight differences between these 2 forms please. deviation caused on following line of code if not adicta , not adictb: both equal {} , yet if condition didn't return true. line of code changed to if not adicta=={} , not adictb=={}: and code worked expected. you right in thinking empty dictionaries false in boolean context. therefore, not {} , empty_dict == {} equivalent, however... in first one, checking if false . >>> not {} true but in second one, checking if empty (therefore false ) , reversing not . >>> not not {} # doing. false you different results because not testing same condition.

ptrace - Does android support the PTRACE_SINGLESTEP? -

ok, simple question.does android support ptrace_singlestep when use ptrace systemcall? when want ptrace android apk program, find can't process singlestep trace. situation changed when use ptrace_syscall, can work perfectly. android wipe out function or arm lack supports in hardware? appreciated!thanks. this core program: int main(int argc, char *argv[]) { if(argc != 2) { __android_log_print(android_log_debug,tag,"please input pid!"); return -1; } if(0 != ptrace(ptrace_attach, target_pid, null, null)) { __android_log_print(android_log_debug,tag,"ptrace attach error"); return -1; } __android_log_print(android_log_debug,tag,"start monitor process :%d",target_pid); while(1) { wait(&status); if(wifexited(status)) { break; } if (ptrace(ptrace_singlestep, target_pid, 0, 0) != 0) __android_log_print(android_log_debug,tag,"ptrace_singlestep attach error...

udp - Simulate packet loss in C program language -

i have udp server/client code written in c , want simulate packet loss because packet loss on wireless network high , can not perform tests switched ethernet. example want have 20 % packet loss, how can in c ? thx i'm not sure want simulate network interuptions in application, test show simulation works. have simulate loss of packets outside of application. you can add iptables rules doing : # randomly dropping 20% of incoming packets: iptables -a input -m statistic --mode random --probability 0.2 -j drop # , dropping 20% of outgoing packets: iptables -a output -m statistic --mode random --probability 0.2 -j drop http://code.nomad-labs.com/2010/03/11/simulating-dropped-packets-aka-crappy-internets-with-iptables/

ios - Multiple methods named 'location' found with mismatched result, parameter type, or attributes -

i have read other questions concerning multiple methods still not know how fix code. grateful this. have put * around statement error occurs. - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath: (nsindexpath *)indexpath { static nsstring *cellidentifier = @"eventcell"; eqcalendarcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; if (cell == nil) { cell = [[eqcalendarcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifier]; } cell.titlelabel.text = [[self.eventslist objectatindex:indexpath.row] title]; cell.locationlabel.text = [[self.eventslist objectatindex:indexpath.row] location]; nsdateformatter *df = [[nsdateformatter alloc] init]; [df setdateformat: @"dd-mm-yy hh:mm"]; nsstring *startdatestring = [df stringfromdate:[[self.eventslist objectatindex:indexpath.row] startdate]]; cell.startda...

php - Classic API pt-BR Forum Submission (UK Account) -

hopefully here can hope basic question. i'm creating basic form donation amount in brazilian real, when submit button pressed re-directs uk paypal site in english (which means people submitting donation dont understand it). amount goes though correctly in brl there way force site use pt-br language? i've tried using https://www.paypal.com.br/cgi-bin/webscr , https://www.paypal.com/br/cgi-bin/webscr in action neither work. anyone have ideas please? paypal saying need register br paypal account (which cant dont have bank account on there) <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="currency_code" value="brl"> <input type="hidden" name="lc" value="pt-br"> <input type="hidden" name="doexpresscheckoutpayment" value="br"> <input type="hidden" name="setexpresscheckout...

distributed - What CAP-Type does LevelDB(RocksDB) have? -

during evaluation of several distributed systems came across cap-theorem. unfortunately can't find classification leveldb or more specific rocksdb. here actual question: kind of cap-type leveldb/rocksdb , why? leveldb , rocksdb not distributed databases. hence, brewer's cap theorem inapplicable.

Insert row on top of pandas dataframe with index 1 day before -

i have pandas dataframe index consisting of dates daily frequency. how possible add row on top of dataframe index one-day before first element of original dataframe? thanks regards you sort dataframe after add new element using, df.sort()

c - Finding the highest rank of all the processes -

i trying learn mpi. how find out process with highest rank within mpi_comm_world in mpi 3? mpi_init(&argc, &argv); mpi_comm_rank(mpi_comm_world, &my_rank); mpi_comm_size(mpi_comm_world, &p); //more code here mpi_finalize(); i know mpi_comm_rank(mpi_comm_world, &my_rank); me rank of calling process, find highest rank of processes in mpi_comm_world can make process computations. to highest ranking process, can use mpi_comm_size(mpi_comm_world, …) determine total number of process on mpi_comm_world communicator. since every process part of communicator, , process enumerated 0, rank of highest ranking process subtract 1 mpi_comm_world's size: int size = mpi_comm_size(mpi_comm_world, &size); int highest_rank = size - 1;

windows - Kernel32 CopyFile does not find a file which exists c# -

i invoked kernel32's copy file method that: [dllimport("kernel32.dll", charset = charset.unicode, callingconvention = callingconvention.stdcall, setlasterror = true)] [return: marshalas(unmanagedtype.bool)] static extern bool copyfile( [marshalas(unmanagedtype.lpstr)] string lpexistingfilename, [marshalas(unmanagedtype.lpstr)] string lpnewfilename, [marshalas(unmanagedtype.bool)] bool bfailifexists); [dllimport("kernel32.dll")] public static extern uint getlasterror(); however when call it return 2 getlasterror() means file not found. path exists. string newfile = environment.currentdirectory + "\\temp" + path.getextension(file); uint i; if (!copyfile(file, newfile, true)) = getlasterror(); i'm trying bypass longpath exception solution. doesn't seem work normal files. appreciated. here's complet...

selenium - How to get the text only from the child element - Webdriver - Java -

i trying text child element. see below: <strong class="envmain"> <strong id="currentclock">11:19</strong> gmt </strong> i gmt text. i tried writing xpath like: .//*[@id='userenvironmentinfo']/div[2]/a/strong/text()] way element not found. thanks in advance. update of html: <div class="datetime"> <a class="envpicker" title="change timezone" href="javascript:void(0);"> <span class="envdd">▾</span> <span class="envicon datetimeicon">the time is:</span> <strong class="envmain"> <strong id="currentclock">17:34</strong> gmt </strong> <span id="currentday" class="envmore">monday</span> <span id="currentdate" class="envmore">14.04.2014</span> </a> <div class="envcontainer"> ...

android - Button focused state getting lost : Google TV -

in google tv application, there around 6 buttons pressed, focused, enabled etc. states them. all buttons have got same pressed, focused, enabled etc. states in xml file below. <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/default_bt" android:state_enabled="true" android:state_pressed="true"/> <!-- pressed --> <item android:drawable="@drawable/default_bt" android:state_enabled="false" /> <!-- disabled --> <item android:drawable="@drawable/default_bt_hvr" android:state_focused="true"/> <!-- focused --> <item android:drawable="@drawable/default_bt_hvr"/> <!-- default --> </selector> using google tv remote, if start moving left side, buttons shifting focus , when reach leftmost button, focus remains on leftmos...

ios7 - Getting wifi Router type in iOS -

i want know if there ios api available can used find out kind of router connected to.. ex:- if wifi router g type router or n type router. application have needs identify kind of router connected & based on start proceeding next steps. any appreciated. i don't think sort of info send on wifi signal. unless hack router , pull details. can not check speed , determine n/g etc based on that?

php - CSS class not getting reflected in the table -

i have values in table on upon click want set particular class , navigate page. table looks this: <?php // form page file name if($content_type == "") { $content_type = "wtc"; } ?> <table border='0' width='250' class='navigation'> <tr> <td align='left' valign='right' class=<?php if($content_type == "wtc") echo 'active'; ?>><a href='?page=wtc'>create wtc server</a></td> </tr> <tr> <td align='left' valign='right' class=<?php if($content_type == "rap") echo 'active'; ?>><a href='?page=rap'>create rap</a></td> </tr> <tr> <td align='left' valign='right' class=<?php if($content_type == "lap") echo 'active'; ?>><a href='?page=lap'>create lap</a...

android - auto switch back to low profile mode after seconds delay -

quick question. can dim soft buttons using system_ui_flag_low_profile flag. when click them , stay in "normal profile" ever after. should make them stay hidden again after seconds of idleness? you can listen changes in system ui using view.onsystemuivisibilitychangelistener . , can use handler postdelayed runnable rehide again. @override public void onsystemuivisibilitychange(int visibility) { new handler().postdelayed(new runnable() { @override public void run() { //todo: hide system ui again. } }, 100); }

java - Close the JInternalFrame through JMenuItem -

hi creating internal frame, want close internalframe through menu item closed total frame. please me. here code, public class closewindow extends javax.swing.jframe { jtextarea tx; int i=0; public closewindow() { initcomponents(); } @suppresswarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="generated code">//gen-begin:initcomponents private void initcomponents() { tpane = new javax.swing.jtabbedpane(); jmenubar1 = new javax.swing.jmenubar(); jmenu1 = new javax.swing.jmenu(); crete = new javax.swing.jmenuitem(); close = new javax.swing.jmenuitem(); setdefaultcloseoperation(javax.swing.windowconstants.exit_on_close); jmenu1.settext("file"); crete.settext("create"); crete.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent ev...

encoding - How to save bits to a file in Go -

i want serialise data in go , have write individual bits. (specifically huffman encoding). best way this? obvious way take 8 bits @ time , shift first 1 7 places left, 6 next 1 , on. i wondering whether or not there more idiomatic way this, possibly function in standard library. i've had @ encoding/gob, not seem offer control wish, example writing slice of 4 booleans (which have thought corresponded bits) outputed 24 bytes. i'm guessing has numbers signify slice start, boolean next etc. is there way this? encoding/gob binary encoding go values. has nothing ever bit operations. it's main purpose provide performant solution transfering go datastructures on network connections etc (especially rpc package). golang's internal representation of slices struct containing pointer array (of appropriate type), , 2 ints, 1 len gth (i.e. number of elements in slice) , cap acity (i.e. ammount of memory allocated array. i don't think there support in standard ...

How can I get iTerm to use the newer version of bash that brew shows? Change a user's shell on OSX -

when brew upgrade i see have newer version. how can use it? $ bash -version gnu bash, version 3.2.51(1)-release (x86_64-apple-darwin13) copyright (c) 2007 free software foundation, inc. $ brew upgrade bash error: bash-4.2.45 installed $ bash /bin/bash i see have /usr/local/cellar/bash/4.2.45/bin but when do $ /usr/local/cellar/bash/4.2.45/bin/bash i still in $ bash -version gnu bash, version 3.2.51(1)-release (x86_64-apple-darwin13) copyright (c) 2007 free software foundation, inc. 08:06:45 mdurrant w89123148q1 /usr/local/cellar/bash/4.2.45/bin master the contents of /etc/shells are: /usr/local/cellar/bash/4.2.45/bin/bash # (i added this) /usr/local/bin/bash /bin/bash /bin/csh /bin/ksh /bin/sh /bin/tcsh /bin/zsh chsh didn't seem hoped: $ chsh -s /usr/local/cellar/bash/4.2.45/bin/bash changing shell mdurrant. password mdurrant: chsh: /usr/local/cellar/bash/4.2.45/bin/bash: non-standard shell $ bash --version gnu bash, version 3.2.51(1)-release (x86_64-ap...

sql server - ADODB RecordCount behaviour changes calling SQL stored procedure with EXEC? -

i'm maintaining vb6 application uses sql server via adodb. rewrote lines sql = "exec sp_mystoredproc " & format(iparam1) & "," & format(iparam2) call rs.open(sql, cn, 1, 1) as dim cmd new adodb.command cmd.commandtype = adcmdstoredproc cmd.commandtext = "sp_mystoredproc" cmd.parameters.append cmd.createparameter("@iparam1", adinteger, adparaminput, , iparam1) cmd.parameters.append cmd.createparameter("@iparam2", adinteger, adparaminput, , iparam2) cmd.activeconnection = cn rs.open cmd, , 1, 1 it looked simple..., after change, rs.recordcount returns -1. i have fixed problem forcing cn.cursorlocation = aduseclient before rs.open statement, question is: does have idea why calling stored procedure via adodb.command of type adcmdstoredproc provides different cursor behaviour sending "exec..." statement server?

c# - Ksoap2 : Calling DateTime datatype on .NET Web Service -

i have wcf web service. service have tested on .net platform. i use ksoap 2 generate java classes file consume service. when use ksoap2, datetime datatype becomes string (due java doesn't have datetime datatype comparable datetime in .net) so, @ getter attribute object, don't know how set value : for example : student.birth = "12/12/2013" student.birth = "2013/12/12" i have tested on case, maybe because format not true, exception : this value cannot set null i don't know value. guess birth field above. so. question : how use datetime data type in ksoap ? structure should put in datetime string ? thanks :) my guess use datetime.format strings http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx public class dateexample { private datetime _dt; public string dt { { return _dt.tostring("hh:mm:ss tt", system.globalization.cultureinfo.invariant...

django - invalid literal for int() with base 10: -

in view, error message: invalid literal int() base 10 views.py author_id = request.post.get('id_author') input_author= engineer.objects.get(id=author_id) the items in post dictionary strings default. must convert them integers using int method: author_id = int(request.post.get('id_author')) input_author = engineer.objects.get(id=author_id)

mongodb - Push element in any position of array in the subdocument -

in mongodb 2.6 can use $position ( http://docs.mongodb.org/master/reference/operator/update/position/ ) modifier specifies location in array during update of array in document . insert in array in subdocument . document schema: { subdoc: { array: ['0', '1', '2', '5', '6'] } } the following update pushes elements in end of array .. db.collection.update( { _id: tsid }, {$push: { 'subdoc.array': { $each:['3', '4'], $position:3 } }}); so, result { subdoc: { array: ['0', '1', '2', '5', '6', '3', '4'] } } but expect { subdoc: { array: ['0', '1', '2', '3', '4', '5', '6'] } } is possible in mongodb 2.6? it's fair proposition in question, have concept wrong. the first of have missed concept arrays in general have entries starting @ index of 0 first ele...

node.js - JavaScript code substitution on client side -

i'm learning new technologies (such node.js, socket.io, redis etc.) , making simple test applications see how can work. my question security on client-side javascript code: example, have chat-server on node.js+express , when user connects chat, server should assign registred username (authorisation through oldschool php+mysql used) socket. question is, can user modify client-side script , connect chat under different users' names? some code given below: (server-side part of assigning username, getting username client-side call) // when client emits 'adduser', listens , executes socket.on('adduser', function(username){ // store username in socket session client socket.username = username; // store room name in socket session client socket.room = 'general'; // add client's username global list usernames[username] = username; // send client room 1 socket.join('general'); // echo client they've ...

python - Lowering process priority of multiprocessing.Pool on Windows -

i use multiprocessing.pool() parallelize heavy pandas processing find bit successful. cpu usage goes 100% , entire computer becomes unresponsive. mouse becomes difficult use. i can change process priority of process code. import psutil p = psutil.process(os.getpid()) p.nice = psutil.below_normal_priority_class however, when in windows task manager find main python.exe process has been changed below normal priority. is there way reduce priority of pool processes? you can try setting priority of process' children after spawned them. like: import psutil # spawn children and/or launch process pool here parent = psutil.process() parent.nice(psutil.below_normal_priority_class) child in parent.children(): child.nice(psutil.below_normal_priority_class)

javascript - Cross-platforms WPF application with WebBrowser -

i'm looking best way develop cross-platforms (windows, ios, android) wpf application embedded webbrowser. should load html/javascript page , allow communication between javascript , c#, in both side. i can use xamarin, "web browser object" each os. communication c# -> javascript can implemented differently each os. however, communication javascript -> c# should stay same. how can use c# methods without using "window.external" (specific wpf webbrowser) ? possible without using framework phonegap ? thanks "wpf" acronym windows presentation foundation , technology part of .net framework , built upon core windows components such directx. it not work in other platforms except windows (the full, desktop version of windows). doesn't run in rt version of windows can find in portable devices such tablets. if need cross-platform app, either use web technologies (html + javascript) or use product xamarin build native apps on diffe...

css3 - Bootstrap dropdown at footer? -

i have issues bootstrap dropdown in footer menu? here example talking about? http://www.bootply.com/129846 try click on dropdown in footer, see happen, go under page, , new scroll appear? try add dropdown footer of page <div id="footer"> <div class="container"> <li class="dropdown"> <a href="#" data-toggle="dropdown" role="button" id="drop5" class="dropdown-toggle">dropdown 2 <b class="caret"></b></a> <ul aria-labelledby="drop5" role="menu" class="dropdown-menu" id="menu2"> <li role="presentation"><a href="#" tabindex="-1" role="menuitem">action</a></li> <li role="presentation"><a href="#" tabindex="-1" role="menuitem...

php - Get URL of external site accessing my file -

i have script on server many sites use: mysite.com/counter.php other sites using file command "file_get_contents" how can url of sites accessing file? i echo via mysite.com/counter.php file whenever external sites accessing it: thank other_site_url_here using our script it can't done file_get_contents , consider using tokens database. people want script register , special token. then, they'd use script tokenized url, like: mysite.com/myscript/fs9dfyb87sdf8s . able collect stats token.

linux - Running a C file from within another C file in Ubuntu -

i need run c program within c program on ubuntu. scanf //say i=2 entered switch (i){ case 1: print xyz; break; case 2: cc abc.c -lpthread (and then) ./a.out //execute command execute file name abc break; } how that? searched google thoroughly couldn't find suitable answers. edit: running said execute command bash file. works , solves requirement in easy way :d #! /bin/bash read if [ $a -eq 1 ] cc ex.c -lpthread ./a.out else echo "hi" fi you need make use of fork() , exec() spawn off subprocess ( regardless of process doing - note you're compiling , running new process). if want spawn off process , wait it, relying on return (error) code determine success, system() option.

unit testing - Android Test : ActivityInstrumentationTestCase2 : Test 2 buttons, where each one navigates to another activity -

i trying make android tests application. have activity (a) contains 2 buttons, each 1 navigating activity (b) different (data) in intent. i able test 1 of them, not both. because when perform click of first, navigate next activity (b) , second button not visible anymore. my question : 1- possible make many case of tests in same activity ? 2- there way or best practice creat many cases scenarios test ? example ---> click in first button , navigate activity (b) , restart activity (a) again, , click in second button ? thanks anyway. this code of activitytest : public class myactivitytest extends activityinstrumentationtestcase2<myactivity> { /** * first button. */ view abutton; /** * second button. */ view bbutton; /** * activity under test. */ myactivity activity; /** * create new myactivitytest. */ public myactivitytest() { super(myactivity.class); } /* * (non-javadoc) ...

JDBC resource shared between webapps in Tomcat -

i have such configuration of database in tomcat instance (h2): <resource name="jdbc_ttds" auth="container" type="javax.sql.datasource" driverclassname="org.h2.driver" url="jdbc:h2:***;ifexists=true" username="**" password="**" maxactive="20" maxidle="5" maxwait="-1" /> i want have 2 applications in instance, connect through jndi. h2 thread-safe, file locked during tomcat running. am able have 2 jndi connections inside tomcat 2 different apps? is safe, because 1 of applications insert/drop db, while select it. however, both have concurrent connections db. if impossible or unsafe, best idea run h2 in server mode?

gis - Postgis ST_Transform -

i have point (x, y) srid 900913. transform srid 2180 , again srid 900913. imo should have same point, differs. why? select st_x (st_transform(st_transform(st_geomfromtext('point(21.01233628836129 52.23044648850736)', 900913), 2180), 900913)), st_y(st_transform(st_transform(st_geomfromtext('point(21.01233628836129 52.23044648850736)', 900913), 2180), 900913)); the quick answer why 2 transformations different because of common confusion of projection systems. the coordinate point(21.01233628836129 52.23044648850736) on spherical mercator projection @ 0°0'1.689"n 0°0'0.680"e , way outside poland, makes difficult or typically impossible reproject else. the coordinates looking @ most likely longitude/latitude on wgs 84 (epsg:4326) . i think exercise attempting ( latlon_check in particular): select st_aslatlontext(geom) latlontext, st_aslatlontext(st_transform(st_transform(geom, 2180), 4326)) latlon_check, st_astext(st_transfo...

java library which enables composing futures (flatMap) asynchronously -

i thought new java 8 completablefuture able execute async tasks, 1 after without blocking threads, using "thencomposeasync" method. i think not case. thread waits synchronously task completed (completablefuture.java:616 r = fr.waitingget(false);) and following piece of code never executes "task 3" if nthreads <= 2: int nthreads= 2; executor e= executors.newfixedthreadpool(nthreads); completablefuture.runasync( () -> { system.out.println("task 1 threadid " + thread.currentthread().getid()); }, e).thencomposeasync( (void v1) -> { return completablefuture.runasync( () -> { system.out.println("task 2 threadid " + thread.currentthread().getid()); }, e).thencomposeasync((void v2) -> { return completablefuture.runasync( () -> { system.out.println("task 3 threadid " + thread.currentthread().getid()); }, e); }, e); }, e).join(); system.out.println("finished...

soap - How to search for XML elements in python? -

Сode shown below works perfectly, problem need manually set name-spaces d: . possible somehow search elements ignoring name-spaces dom.getelementsbytagname('scopes') ? def parsesoapbody(soap_data): dom = parsestring(soap_data) return { 'scopes': dom.getelementsbytagname('d:scopes')[0].firstchild.nodevalue, 'address': dom.getelementsbytagname('d:xaddrs')[0].firstchild.nodevalue, } since code uses parsestring , getelementsbytagname , i'm assuming using minidom. in case, try: dom.getelementsbytagnamens('*', 'scopes') it doesn't in the docs , if in source code xml/dom/minidom.py , you'll see getelementsbytagnamens calls _get_elements_by_tagname_ns_helper defined this: def _get_elements_by_tagname_ns_helper(parent, nsuri, localname, rc): node in parent.childnodes: if node.nodetype == node.element_node: if ((localname == "*" or node.local...

javascript - Remember scroll position on navigating back to first page from second one -

if having page loading content ajax on scrolling bottom,if click on link on scrolling down position on page , navigate next page.and when next page,i press button ,i want page go same position cliked. please guide me how can done. on navigating second page can send position via querystring , querystring on page using javascript , vice versa similarly.lets navigated on page2 'page2.html?position=44' here code querystring: javascript: function getquerystring(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new regexp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeuricomponent(results[1].replace(/\+/g, " ")); } usage: var position = getquerystring('position'); hope helps.

With the PHP Riak Client, how would I search two indexes for values simultaneously? -

i have dataset in riak different items indexed (using index_bin ). how go searching objects 2 of these indexes have particular values in single request? example: gender, last_name gender = male, , last_name = smith would use map/reduce? if so, example code? a limitation of secondary indexes in riak single index can searched @ time. therefore not able directly combine indexes. as index data stored in metadata of record, create mapreduce job takes 1 2i query input , has map phase filters on other based on metadata. using mapreduce way may quite slow , inefficient data passed map phase function need read disk. if looking serve reasonably common , predictable request, can create , use composite index instead. e.g. create index named gender_name_bin have values male_smith . allow range query on last part of index long first part fixed, gives flexibility. it in recent versions possible filter secondary index values based on regular expressions, not require actual objec...

osx - Updating my Mac's OpenSSL, what am I doing wrong? -

i'm updating openssl on mac os x 10.8.5. updated using below commands , seems have succeeded. wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz tar xzf openssl-1.0.1g.tar.gz cd openssl-1.0.1g ./configure darwin64-x86_64-cc make sudo make install however, when "openssl version" still "openssl 0.9.8y 5 feb 2013" though did make install 1.0.1g. missing step here? however, when "openssl version" still "openssl 0.9.8y 5 feb 2013" though did make install 1.0.1g. missing step here? the openssl built , installed located in /usr/local/ssl . program openssl located in /usr/local/ssl/bin , headers located in /usr/local/ssl/include/openssl , , libraries located in /usr/local/ssl/lib . you using openssl came mac os x in /usr/bin : $ find /usr -iname openssl /usr/bin/openssl ... you can examine details of openssl installed using full path: $ /usr/local/ssl/darwin/bin/openssl version -a openssl 1.0.1g-fips 7 apr 20...

c# - How to serialize a list of string values with attributes -

i have problem. how serialize list of string entries have attributes well? <xml> <metadata> <entry key="key1">string1</entry> <entry key="key2">string2</entry> <entry key="key3">string3</entry> </metadata> </xml> i know how without attributes, don't have idea how same in case: [serializable] [xmlroot(elementname = "xml")] public class myxml { [xmlarray(elementname = "metadata")] [xmlarrayitem(elementname = "entry")] public list<string> metadata { get; set; } } you need create separate class hold xmlattribute , xmltext . public class entry { [xmlattribute("key")] public string key { get; set; } [xmltext] public string value { get; set; } } [serializable] [xmlroot(elementname = "xml")] public class myxml { [xmlarray(elementname = "metadata")] ...

cmd - Putting output file into var -

i have easy .bat file %2 >file.tmp set /p %1=<file.tmp i expect use script in way: putvar var1 command.bat it should first line of output command.bat variable var1 , after should able use var1 variable, example putvar var1 command.bat echo %var1% unfortunately not work. how work? maybe there easier way? your problem in sample code command running ( command.bat ) batch file, being invoked inside batch file, , if batch file call batch file without using call command, execution not return caller batch. to keep syntax, can use (cmd /c "%~2")>file.tmp set /p "%~1="<file.tmp spawning second instance of cmd handle command, redirecting output temporary file , reading file (only first line of command.bat output) variable. a simpler way of doing use for /f for /f "delims=" %%a in ('%~2') set "%~1=%%a" which, more or less, same work. run command retrieve output and, in case, iterate on output of co...

jquery - Angularjs show-hide -

im trying re-write of application using angularjs.. far i've used jquery , made use of .show , .hide example: example.html <div> <ul> <li> <div class="home-heading">home</div> </li> <li> <div class="products-heading">products</div> </li> <li> <div class="about-heading">about us</div> </li> <li> <div class="contact-heading">contact us</div> </li> </ul> </div> <div class="home"> welcome home </div> <div class="products"> welcome products </div> <div class="about"> welcome </div> <div class="contact"> welcome contact </div> show.js $('.home-heading').on('click', function()...

php - How can I get IDE autocomplete for PHPUnit if I installed from source? -

i know seems duplicate, problem different: since installed php source, folders not there. installed phpunit usual way using pear. normally add /usr/share/php include path of ide or project , done. folder doesn't exist. $ updatedb $ locate phpunit /usr/local/bin/phpunit /usr/local/lib/php/.channels/pear.phpunit.de.reg /usr/local/lib/php/.channels/.alias/phpunit.txt /usr/local/lib/php/.registry/.channel.pear.phpunit.de /usr/local/lib/php/.registry/.channel.pear.phpunit.de/phpunit.reg $ locate phpunit /usr/local/lib/php/doc/phpunit /usr/local/lib/php/doc/phpunit/license /usr/local/lib/php/doc/phpunit/readme.md i tried including /usr/local/lib/php, still "undefined class phpunit_framework_testcase" note php , phpunit work fine, need ide autocompletion. what can do? as of phpunit v4 pear distribution contains phar version instead of lots of individual files. , there 1 file ( phpunit ) instead of launcher + php files (on installation phpunit.phar ge...

java - Eclipse RCP. How to change method in org.eclipse.ui.internal -

how change implementation method? istatus restorestate() in class: org.eclipse.ui.internal.workbench; you can't, internal classes out of bounds - eclipse api rules of engagement . the method restorestate not exist in eclipse 4.3 version of workbench .

sql server - Get indicator value for unbound columns without calling SQLGetData() -

is there generic solution null/notnull status column without using sqlbindcol() ? for blob/memo columns in odbc result set, drivers provides limited support sqlgetdata() function. example: if there 2 blob columns 3 , 4, data column 3 must read before reading 4. , after reading 4, it's not possible read 3. so if abstraction layer provides resultset.column(4).isnull() , isnull() implementation must use sqlgetdata() check sql_null_data . after this, can't use resultset.column(3).read(buf) - or similar functions (okay, can read blobs/memo after sqlfetch() step step buffer avoid issues such buffering bad inside abstraction layer...). one solution bind small buffer , sqllen value indiciator via sqlbindcol() . sqlfetch() return sql_null_data in sqllen indiciator value if value (blob, etc.) null, without need of calling sqlgetdata() . but drivers microsoft native client odbc driver can't use sqlgetdata() on bounded columns. if indicator non-null, it...

javascript - Can you create code for an iPhone 'Add to Home Screen' button to put on a webpage? -

when view webpage on safari/iphone there icon/button @ bottom of browser can click (it's square arrow in it), , on drawer opens there button called 'add home screen' (ios7) allows add icon/link iphone's home screen links aforementioned webpage. does know way add button actual webpage allows people same above people viewing on iphone? realise replicate button appears in safari browser, many non-tech users unlikely pay attention these safari buttons , if created button more context allow visitors more add icon home screen easy access webpage. you can't webpage, via feature provided mobile safari. you add like this website. prompts user , calls out location of button add page home screen. https://github.com/cubiq/add-to-homescreen

javascript - Restrict login to specific domain using Node Passport with Google Auth -

i implementing google auth on internal service @ work. js client heavy application node backend. choosing use node module passport.js passport-google-oauth strategy. i have got working 1 thing still confusing me. want ensure application allows company employees login. understand can restrict login domain using parameter called "hd", according official documentation . firstly, send parameter in context of passport.js? don't understand in code put. if helps, have been following the example passport-google-oauth provides . secondly, in theory how work? on google side, reject trying access app domain outside of our company. or on side, need check domain user logging in from? here's example: // first make sure have access proper scope on login route app.get("/login", passport.authenticate("google", { scope: ["profile", "email"] }); // set google oauth strategy elsewhere... passport.use(new googlestrategy({ ...

node.js - how to bypass/avoid crsf on API post? -

in node application expressjs have crsf middleware enabled. works great, have routes starting /api , accepting post request fail (forbidden) because there no crsf token of course. how can bypass/avoid crsf /api posts? you can conditionally pass inside of middleware, 1 option pattern this: function yourmiddleware(req, res, next) { if ( null !== req.path.match(/^\/api/) ) { next(); } //your crsf behavior here }

rest - RESTful way to request an action? -

if part of restful api looks this: post transactions?auth_code=[code] and part of post email address server can send receipt , @ later time client wants have receipt sent again, how create api that? server returns transactionid post. should this: put transactions/[transactionid]?auth_code=[code]&requestreceipt=yes thanks. i invert post/put calls. put create new (in case transaction email address) , post resend receipt. if post in endpoint (/transactions/[transactionid]) used resend confirmation, omit requestreceipt parameter.

jquery - invoke javascript on button click of a datatable row -

im using datatable , have following: var otable = $('#example').datatable({ bprocessing: true, sajaxsource: "/cart/addresses", 'idisplaylength': 5, aasorting: [], aocolumns: [ { "mdata": "contact" }, { "mdata": "address" }, { "mdata": "postcode" }, { "mdata": null, "mrender": function (data, type, full) { return '<button type="button" class="btn btn-success use-address" onclick="dofunction();" role="button" data-adcode="' + full.adcode + '">' + 'use address' + '</button>'; } } ] ...

javascript - Additional parameter for index page sort collection -

i have page renders question objects set of <div> 's. (i use pagination don't think it's of significance particular problem). i give user opportunity choose order in items displayed (aka order of underlying question list. i figured using <select> list simple way, doesn't seem working. i'm struggling calling action controller javascript. have far: my html: <select id="sort-select" style="margin-bottom: 10px"> @foreach (sortingtype value in enum.getvalues(typeof (sortingtype)).cast<sortingtype>()) { <option value="@((byte)value)">@(value.tostring())</option> } </select> (sortingtype enum conatining 3 constants.) my javascript: function addsort() { var select = document.getelementbyid('sort-select'); select.onchange = function(event) { var selected = select.options[select.selectedindex].value; var url = encodeuri("@url.ac...

c++ - Getting error message "Not declared in scope" -

this question has answer here: why helloworld function not declared in scope? 9 answers i working on c++ project , while compiling, receiving error messages: error: mean not declared in scope error: standard_dev not declared in scope my code #include <iostream> #include <iomanip> #include <fstream> #include <cmath> #include <string> using namespace std; int main() { int n(0); char filename[100]; double m, stdev; string temp; double next; int count = 0; cout << "enter name of file: "; cin >> filename; ifstream myfile; myfile.open(filename); while (myfile >> next) { count++; } n = count; double* mydata; mydata = new double[n]; (int = 0; < n; i++) { myfile >> mydata[i]; } m = mean(mydata, n...