Tuesday, 15 July 2014

ios - Using baseurl in UIWebView -



ios - Using baseurl in UIWebView -

i have issues loading site apparently has needing set baseurl. main site http://www.oklahomachristianacademy.org , site address need have open string returns

applewebdata://f6224b10-25ed...

so, in code thought work set baseurl , string attached above load app.

-(void)viewwillappear:(bool)animated { nsurl *theurl = [nsurl urlwithstring:@"http://www.oklahomachristianacademy.org/"]; [savedweb loadhtmlstring:(nsstring *)link baseurl:(nsurl *)theurl]; }

however, not work, , uiwebview displays applewebdata:// line again. missing?

use code

//nsstring *urladdress = @"http://www.google.com"; nsstring *urladdress = @"http://cagt.bu.edu/page/iphone-summer2010-wiki_problemsandsolutions"; //create url object. nsurl *url = [nsurl urlwithstring:urladdress]; //url requst object nsurlrequest *requestobj = [nsurlrequest requestwithurl:url]; //load request in uiwebview. [webview loadrequest:requestobj];

ios uiwebview base-url

iphone - Alternate way to get object based on indexPath in UITableView -



iphone - Alternate way to get object based on indexPath in UITableView -

i next tutorial: http://www.devx.com/wireless/article/43374 add together alphabet sorting , panning uitableview of songs , have finished coding method have followed slows downwards uitableview filtering arrays , retrieving values in cellforrowatindexpath method. cant figure out how can remove excess coding increment speed. mpmediaitems stored in tabletracks array. initialized in viewdidload. , thee musicindex array of alphabets(first letter of each song). extended mpmediaitem include nsstring firstletter first letter of song.

any help speeding up?

-(uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath{ //--create cell--\\ ......... //--load info--\\ nsstring *alphabet = [musicindex objectatindex:[indexpath section]]; nspredicate *predicate = [nspredicate predicatewithformat:@"firstletter beginswith[c] %@", alphabet]; nsarray *songs = [tabletracks filteredarrayusingpredicate:predicate]; //needed object mpmediaitem *item = [songs objectatindex:indexpath.row]; //--rest of method--\\ ........... homecoming cell; }

if showing separate sections, 1 each letter of alphabet, create array of dictionaries data, in viewdidload, not here. dictionaries have first letter of song key, , array of songs value. way, filtering , sorting done front, rather in each row table populated.

iphone objective-c xcode uitableview mpmediaitem

python with for loop -



python with for loop -

this question has reply here:

how maintain python print adding newlines or spaces? 14 answers

hey i've got problem loop, allow want accomplish printing "#" signs 5 times loop out space , in 1 line.

for in range(5): print "#",

can how ride of space in between looks ##### instead of # # # # #???

i assume plan on doing things in loop other printing '#', if case have few options options:

import sys in range(5): sys.stdout.write('#')

or if determined utilize print:

for in range(5): print "\b#",

or:

from __future__ import print_function in range(5): print('#', end='')

if want print '#' n times can do:

n = 5 print '#'*n

or:

n = 5 print ''.join('#' _ in range(n))

python loops for-loop space

php - Twilio - forward call after 2 rings -



php - Twilio - forward call after 2 rings -

is possible using twilio forwards incoming phone call phone number (assume 416-555-1234), , if phone number busy or doesn't reply after 2 or 3 rings, forwards phone number b?

the xml looks right now:

<xml version="1.0" encoding="utf-8"?> <response> <dial> <number> 416-555-1234 </number> </dial> </response>

here's 1 of places phone network gets little odd. ringing hear recording.. no synchronization or relationship else. also, starts network starts connecting call, not 1 time physical device on other end starts ringing. more apparently calling internationally (the caller) might have heard 10 rings receiver has rung 1 time or twice.

anyway, strategy doing isn't hard @ all. you're looking timeout parameter on dial verb: http://www.twilio.com/docs/api/twiml/dial#attributes-timeout

when timer expires, goes on twiml specify. default 30 seconds i've found 15-20 pretty range more responsive forward.

(disclosure: twilio employee here.)

php twilio

visual studio 2010 - How can i get the 2d XNA game tutorial to run on Windows 8? -



visual studio 2010 - How can i get the 2d XNA game tutorial to run on Windows 8? -

i've finished doing 2d xna game tutorial @ college. have screencast demonstrating changes i've made game @ home on windows 8 system. have visual studio 2010 installed , xna 4.0. can open game project in visual c# , ammend part of project need can not run game.

i have tried install windows phone developer tools suggested in xna tutorial when effort installation says "windows 7 or windows vista required.

is there work around can game run can screencast running?

thanks

i ran same problem. far know microsoft dropped xna , stopped back upwards under windows 8 (someone may right me if i'm wrong). not hope lost monogame open source mono port xna framework should work under windows 8.

this link shows how migrate mentioned tutorial monogame , run under windows 8: http://solutions.devx.com/ms/msdn/windows-client/windows-8-xna-and-monogame-part-3-code-migration-and-windows-8-feature-support.html

as far i'm aware monogame's content pipeline doesn't work , still need bake content xnb files.

i hope help

windows visual-studio-2010 xna-4.0

How many languages does .Net support? -



How many languages does .Net support? -

how many languages latest versions of visual studio (2012 , 2010) support?

also, possible create new language in .net?

visual studio 2010 , 2012 straight back upwards c#, vb.net, c++/cli, , f# .net development. there many other languages various levels of "support" well, including ironruby , ironpython, boo, etc.

anybody free create own language on top of cli, , many have done so. wikipedia has long list of .net languages.

.net

xargs with the -d flag, and using substitution, causes an extra "empty" item to be processed -



xargs with the -d flag, and using substitution, causes an extra "empty" item to be processed -

using -d flag in xargs specify delimter seems tack newline after lastly value. either way, causes command break when using substitution stick value middle of command (vs more "standard" way of having xargs pass value end of command).

to rephrase, happens when using -d , -i flags , sticking values middle of command.

how can prepare this?

example:

# echo "server1 server2 server3 server4"|xargs -r -d" " -i+ echo ssh + "sudo service myservice restart" ssh server1 sudo service myservice restart ssh server2 sudo service myservice restart ssh server3 sudo service myservice restart ssh server4 sudo service myservice restart

note lastly command offset newline. not problem if command ended @ newline, in case not.

i've worked around tacking " null" end of list pass xargs, , ignoring resulting error. lousy solution, , unsafe in cases.

my workaround:

# echo "server1 server2 server3 server4 null"|xargs -r -d" " -i+ echo ssh + "sudo service myservice restart" ssh server1 sudo service myservice restart ssh server2 sudo service myservice restart ssh server3 sudo service myservice restart ssh server4 sudo service myservice restart ssh null sudo service myservice restart

xargs isn't tacking on newline; it's since newline isn't delimiter anymore, newline already in input taken literally.

if you're using echo supply input xargs, utilize echo -n doesn't add together newline. if you're using other echo, investigate how can not add together trailing newline, or remove newline using tr or sed or perl or something.

xargs

computer vision - Gaussian smoothing filter -



computer vision - Gaussian smoothing filter -

they have asked me implement 2d gaussian smoothing using separable filter in python. don't know how that... in fact don't know difference 1d , 2d gaussian smoothing. find more info it?

thanks lot

about 2d filtering:

the gaussian smoothing operator 2-d convolution operator used `blur' images , remove detail , noise.

when working images - convolution operation calculates new values ​​of given pixel, takes business relationship value of surrounding neighboring pixels. main element convolution kernel.

Сonvolution kernel - matrix (of arbitrary size, used square matrix (by default, 3x3)

[ ][ ][ ] [ ][k][ ] [ ][ ][ ]

convolution works simply: when calculating new value of selected pixel, convolution kernel applied center pixel. neighboring pixels covered same kernel. next, calculate sum of product of pixels in image values ​​of convolution kernel, covered given pixel. resulting sum new value of selected pixel. now, if apply convolution each pixel in image, effect, depends on chosen convolution kernel.

for illustration have next image:

[47][48][49][ ][ ][ ][ ][ ][ ][ ][ ][ ] [47][50][42][ ][ ][ ][ ][ ][ ][ ][ ][ ] [47][48][42][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]

and have convolution kernel:

[0][1][0] [0][0][0] [0][0][0]

result calculated in followinf way:

result = 47*0 + 48*1 + 49*0 + 47*0 + 50*0 + 42*0 + 47*0 + 48*0 + 42*0 = 48

the result of applying our kernel pixel value of 50:

[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][48][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]

here explanation of gaussian smoothing. 1d , 2d gaussian smoothing:

"the convolution can in fact performed since equation 2-d isotropic gaussian shown above separable x , y components. 2-d convolution can performed first convolving 1-d gaussian in x direction, , convolving 1-d gaussian in y direction. "

you can seek appling convolution filter in site.

hope helpful you.

computer-vision

c# - How to set the Referer of HttpRequest in windows store app? -

This summary is not available. Please click here to view the post.

java - create form in head of main view template -



java - create form in head of main view template -

i have view template contains head, menu, footer (i phone call file main template). template called other pages have content. decided add together form login menu. first thought pass form view file rendered via controller main template parameter don't need show login form everytime on every page would't solution.

i have 2 solution in both have problem:

i created form in main template helper form , input , button pure html

@helper.form(routes.application.loginposted,'class -> "navbar-form pull-right"){ <input class="span2" type="text" placeholder="email" name="email"> <input class="span2" type="password" placeholder="passwd" name="passwd"> <button type="submit" class="btn btn-primary">login</button> }

and handle in controller dynamicform , want transfor form represent model easier validation

dynamicform requestdata = form().bindfromrequest(); form<user_login> loginformfilled = form(user_login.class); loginformfilled.fill(new user_login(requestdata.get("email"), requestdata.get("passwd")));

but loginformfilled.get().email (and passwd too) blank , don't understand why.

i wanted create form in main template model representation can't write code compile (it has problem logform know wrong yet tried lots of combination can't create valid form)

@val logform = new form[user_login] @helper.form(routes.application.loginposted,'class -> "navbar-form pull-right"){ @helper.inputtext( logform("email") ) @helper.inputpassword( logform("passwd") ) <button type="submit" class="btn btn-primary">login</button> }

you don't need utilize dynamicform binding filling form<user_login> can @ 1 time (and that's solution you):

public static result loginapproach(){ form<user_login> loginform = form(user_login.class).bindfromrequest(); string formtostring = loginform.get().email + " pass: " + loginform.get().passwd; homecoming ok(formtostring); }

java playframework-2.1

objective c - Proper memory management with CFStringRef and CFRelease -



objective c - Proper memory management with CFStringRef and CFRelease -

consider simple method; it's category on nsstring.

- (nsstring *)stringbyurlencoding { cfstringref newstring = cfurlcreatestringbyaddingpercentescapes(null, (cfstringref)self, null, (cfstringref)@"!*'\"();:@&=+$,/?%#[]% ", kcfstringencodingutf8); nsstring *returnstring = (__bridge nsstring *)newstring; cfrelease(newstring); homecoming returnstring; }

its job turn = %3d, etc. url encoding, that's not relevant question.

a few questions memory management:

after cfrelease(newstring); called, can still po newstring in debugger , see string. mean it's not getting deallocated properly?

when pass casted cfstringrefs arguments of cfurlcreatestringbyaddingpercentescapes, (like (cfstringref)self, example) believe not need store variable , cfrelease them due "toll-free bridging". correct?

does reply #2 alter if it's cgimageref, not cfstringref? why cgimageref have own cgimagerelease function, there's no cfstringrelease method?

to create sure understanding of __bridge_transfer correct, modified code identical?

- (nsstring *)stringbyurlencoding { cfstringref newstring = cfurlcreatestringbyaddingpercentescapes(null, (cfstringref)self, null, (cfstringref)@"!*'\"();:@&=+$,/?%#[]% ", kcfstringencodingutf8); nsstring *returnstring = (__bridge_transfer nsstring *)newstring; // cfrelease(newstring); homecoming returnstring; }

as questions:

1) don't have plenty info know if newstring should have been deallocated. instance, if no character replacement needed, reasonable cfurlcreatestringbyaddingpercentescapes homecoming equivalent of [self retain]; 1 example. broader point "you can't know." normal approach here utilize instruments heap growth , leaks. more information, google "retaincount useless" (i won't rehash here.)

2) yes.

3) cgimageref not toll-free bridged, however, understand it, cfretain , cfrelease should work. difference between cfrelease , cgimagerelease here parameter cfrelease must not null, whereas cgimagerelease tolerate null parameters.

4) __bridge_transfer appropriate annotation utilize here. "transfers" +1 retain count side arc doesn't handle side handle. set differently, __bridge_transfer tells arc need create release phone call pointer, through never generated retain.

objective-c automatic-ref-counting core-foundation

matlab - Calling generic functions on rows of a matrix -



matlab - Calling generic functions on rows of a matrix -

i'd compute kernel matrices efficiently generic kernel functions in matlab. means need compute k(x,y) every row x of x , every row y of y. here matlab code computes i'd like, rather slow,

function k=compute_kernel( k_func, x, y ) m = size(x,1); n = size(y,1); k = zeros(m,n); = 1:m j = 1:n k(i,j) = k_func(x(i,:)', y(j,:)'); end end end

is there other approach problem, e.g. bsxfun variant calls function on every row taken x , y?

have tired pdist2 custom distance function?

p.s. best not utilize i , j variables in matlab

matlab machine-learning bsxfun

Cocos2d iphone: changing CCSprite.position works on simulator but not on device -



Cocos2d iphone: changing CCSprite.position works on simulator but not on device -

i've got problem cocos2d code, runs fine on simulator (means in case sprites moving when touch , scroll) doesn't work on ipod cctouchesmoved called on both, sprite move in simulator

ccsprite *grada = [ccsprite spritewithfile:@"grad.png"]; grada.anchorpoint = ccp(0, 0); grada.position = ccp(0, 0); [...] -(void) cctouchesmoved:(nsset *)touches withevent:(uievent *)event { //nslog(@"cctouchesmoved called"); uitouch *touch = [touches anyobject]; cgpoint location = [touch locationinview: [touch view]]; location = [[ccdirector shareddirector] converttogl:location]; int d = (_prevtouch.y - location.y); // code should create sprite moving // , on simulator not on ipod grada.position = ccp(paralax_x, grada.position.y - d); _prevtouch = location; } -(void) cctouchesbegan:(nsset *)touches withevent:(uievent *)event { uitouch *touch = [touches anyobject]; cgpoint location = [touch locationinview: [touch view]]; location = [[ccdirector shareddirector] converttogl:location]; _firsttouch = location; } -(void) cctouchesended:(nsset *)touches withevent:(uievent *)event { uitouch *touch = [touches anyobject]; cgpoint location = [touch locationinview: [touch view]]; location = [[ccdirector shareddirector] converttogl:location]; _lasttouch = location; }

btw if "grada.position = ccp(0, grada.position.y - d);" in other method cctouchesmoved works on device , simulator.

it stupid error (and hope is) on side because it's first project.

here how moving sprites @ moment (in cctouchesmoved):

uitouch *touch = [touches anyobject]; cgpoint touchlocation = [self converttouchtonodespace:touch]; cgpoint oldtouchlocation = [touch previouslocationinview:touch.view]; oldtouchlocation = [[ccdirector shareddirector] converttogl:oldtouchlocation]; oldtouchlocation = [self converttonodespace:oldtouchlocation]; cgpoint translation = ccpsub(touchlocation, oldtouchlocation); cgpoint newpos = ccpadd(currentfragment.position, translation); currentfragment.position = newpos;

cocos2d-iphone ios-simulator ccsprite

RPC port Map Failure Mac OSX 10.6 -



RPC port Map Failure Mac OSX 10.6 -

i m trying run programme using rpc of adding 2 numbers on mac osx 10.6

here doing:

rpcgen -a -c add.x

it generates files

add.h,add_clnt.c,add_svc.c,add_server.c,add_client.c

then compile files using:

gcc -g -drpc_svc_fg -c -o add_clnt.o add_clnt.c gcc -g -drpc_svc_fg -c -o add_client.o add_client.c gcc -g -drpc_svc_fg -c -o add_xdr.o add_xdr.c gcc -g -drpc_svc_fg -o add_client add_clnt.o add_client.o add_xdr.o gcc -g -drpc_svc_fg -c -o add_svc.o add_svc.c gcc -g -drpc_svc_fg -c -o add_server.o add_server.c gcc -g -drpc_svc_fg -o add_server add_svc.o add_server.o add_xdr.o

run server in 1 remote console

./add_server

run client in console

./add_client localhost 23 35

23 , 35 number sum want printed on sec console. when execute next nil appears on server console.

if seek ip address instead of localhost while running client error is:

rpc:port mapper failure

i using macosx 10.6

you there.

this done on solaris scheme , should see similar on macosx.

after starting add_server on remote host, check add_server has registered remote portmapper. e.g.

remote> cat add.x struct add_args { int a; int b; }; typedef struct add_args add_args; bool_t xdr_add_args(); #define addprog ((u_long)0x20000001) #define addvers ((u_long)1) #define add together ((u_long)1) extern int *add_1(); remote> ./add_server & remote> rpcinfo -t localhost 536870913 programme 536870913 version 1 ready , waiting

536870913 0x20000001 in decimal. see if remote host can reached local host. if yes, run add_client.

local> ping remote remote live local> rpcinfo -t remote 536870913 programme 536870913 version 1 ready , waiting local> ./add_clnt remote 23 35

osx port rpc

Windows batch: run a process in background and wait for it -



Windows batch: run a process in background and wait for it -

i need start 2 background processes batch job , wait them. unix shell analogue is:

myprocess1 -flags1 & pid1=$! myprocess2 -flags2 & pid2=$! wait ${pid1} wait ${pid2}

any ideas?

you solve it, using start wrapper.

the wrapper starts process start /wait , after process finished deletes file signaling.

the first process start through wrapper, sec can start start /wait. need wait file.

echo > waiting.tmp start cmd /c wrapper.bat myprocess1 -flags1 start /wait myprocess2 -flags2 :loop if exist waiting.tmp goto :loop

content of wrapper.bat

start /wait %* del waiting.tmp

windows batch-file windows-shell

regex - Finding the complement of a DFA? -



regex - Finding the complement of a DFA? -

i asked show dfa diagram , regex complement of regex (00 + 1)*. in previous problem had prove complement of dfa closed , regular look also, know convert dfa, m complement, m`, need swap initial accepting states , final accepting states.

however, appears initial accepting states regex {00, 1, ^} , final accepting states {00, 1, ^} well. swapping them result in exact same regex , dfa seems contradictory.

am doing wrong or regex supposed not have real complement?

thank you

as says in question:

i know convert dfa, m complement, m`, need swap initial accepting states , final accepting states.

its not complement, doing something reverse of language , regular languages closure under reversal.

reversal of dfa

what reversal language ?

the reversal of language l (denoted lr) language consisting of reversal of strings in l.

given l l(a) fa a, can build automaton lr:

reverse edges (arcs) in transition diagram

the accepting state lr automaton start state a

create new start state new automaton epsilon transitions each of take states

note: reversing arrows , exchanging roles of initial , accepting states of dfa may nfa instead. that's why written fa(not dfa)

complement dfa

finding complement of dfa?

defination: complement of language defined in terms of set difference Σ* (sigma star). l' = Σ* - l.

and complement language (l') of l has strings Σ* (sigma star) except strings in l. Σ* possible strings on alphabet Σ. Σ = set of language symbols

to build dfa d accepts complement of l, convert each accepting state in non-accepting state in d , convert each non-accepting state in take state in d. (warning! not true nfa's)

a dfa of l, d complement

note: build complement dfa, old dfa must finish means there should possible out going border each state(or in other words δ should finish function).

complement: reference example

complement dfa regular look (00+1)*

below dfa named a:

but not dfa not finish dfa. transition function δ partially defined not total domain q×Σ (missing out going border q1 lable 1).

its finish dfa can follows (a):

in above dfa, possible transactions defined (*for every pair of q,Σ *) , δ finish function in case.

reff: larn partial function.

new complement dfa d can constructed changing final states q0 not final states , vice-versa.

so in complement q0 become non-final , q1, q2 final states.

now can write regular look complement language using arden's theorem , dfa given.

here writing regular look complement directly:

(00 + 1)* 0 (^ + 1(1 + 0)*)

where ^ null symbol.

some helpful links: here , through profile can find more helpful answers on fa. also, 2 links on properties of regular language: one, second

regex regular-language automata dfa nfa

Escaping "this" or @ character in coffeescript -



Escaping "this" or @ character in coffeescript -

accessing web api i'm getting json response similar to:

example: { @param: 1 }

in javascript, access example.@param in coffeescript, @ reserved word , shortcut this throws error "parse error on line #: unexpected '@'".

how can access variable?

in coffeescript

e={"@param":1}

then

e["@param"] # @param value

e={@param:1} not valid javascript if @param not surrounded quotes , valid json because in json keys must quoted.

coffeescript

cocoa - How to tell if a captured window is being displayed as retina in a retina display? -



cocoa - How to tell if a captured window is being displayed as retina in a retina display? -

if capture window using like...

cgimageref imageref = cgwindowlistcreateimage(cgrectnull, kcgwindowlistoptionincludingwindow, windowid, kcgwindowimageboundsignoreframing);

and window bounds like...

kcgwindowbounds = { height = 150; width = 490; x = 395; y = 174; };

if window on retina display kcgwindowbounds height reported 300 or 150 resultant captured image 300?

thanks in advance, 1 of things without @ retina display i'm not sure , think helpful on developers too...

ok, found reply using quartz-debug enable hidp modes, , dragged window onto screen hidp enabled.

the reply height / width of windows bounds same no matter if retina or not. captured image 2 times larger if beingness displayed on retina screen.

i expected case didnt want create assumptions.

cocoa retina-display

c - Storing and retrieving strings in Multidimensional array -



c - Storing and retrieving strings in Multidimensional array -

i have next code stores string-input user n times in multidimensional array. , print out sec element.

main() { // array store 10 strings, 20 characters long. char strstorage[10][20]; printf("\nenter how many strings: "); scanf( "%d" , &num); fflush(stdin); ( count = 0 ; count < num ; count++) { printf("enter string: "); gets(strstorage[count]); fflush(stdin); } printf("%s", strstorage[2]);

last line prints out garbage. user-input not visible within garbage hence either element access wrong or storage wrong. can help me regards problem?

thanks in advance...

strstorage[2] third string, if num less 3, won't initialize , contain garbage.

c arrays string

javascript - Cannot get Chrome popup.js to use console.log -



javascript - Cannot get Chrome popup.js to use console.log -

i utilize console.log heavily debug when writing js. trying utilize in writing chrome extensions not working. there trickery involved here???

popup.html

<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html> <head> <link type="text/css" rel="stylesheet" href="css/jquery-ui-1.10.0.custom.min.css" /> <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.10.0.custom.min.js"></script> <script type="text/javascript" src="js/popup.js"></script> </head> <body style="width: 200px"> </body>

popup.js

console.log('test1'); $(document).ready(function() { console.log('test2'); });

neither of these appear in js debugger.

even had problem initially... create sure have right developer tool windows opened.. mean, might have opened developer tool windows main page rather extension's page (ie. popup.html). open developer window inspecting popup, right click on popup , click inspect element... opens right developer windows..

i had made stupid error , stuck.. :)

javascript google-chrome-extension

calculate textboxes for each table row in jquery -



calculate textboxes for each table row in jquery -

i looping through set of dynamic table rows, trying capture value of cell2 in each table row using jquery, returns value of cell2 row1 every time, though recognises cells1 right row value each time, can tell me going wrong please? see below sample code.

thanks help received.

//html <table class=planttable> <tr> <td><input type=text value=0 class=cell1></td> <td><input type=text value=0 class=cell2></td> <td><input type=text value=0 class=cell3></td> </tr> <tr> <td><input type=text value=0 class=cell1></td> <td><input type=text value=0 class=cell2></td> <td><input type=text value=0 class=cell3></td> </tr> <tr> <td><input type=text value=0 class=cell1></td> <td><input type=text value=0 class=cell2></td> <td><input type=text value=0 class=cell3></td> </tr> </table> //jquery tr = $(".planttable tr").length; $(tr).each(function () { $(this).find($(".cell1").blur(function () { cell1val = parseint($(this).val()); cell2val = parseint($(".cell2").val()); //returns value of cell2 in first row only? }));

inside find you're finding again, @ document top, finding row1 cell2. if want sibling of current item seem to, this:

$("tr").each(function () { $(this).find($(".cell1")).blur(function () { cell1val = parseint($(this).val()); cell2val = parseint($this.siblings(".cell2").val()); }); });

this retrieve value of cell2 next cell1 found.

jquery

python - Annotating dimensions in matplotlib -



python - Annotating dimensions in matplotlib -

i want annotate lengths in matplotlib figure. example, distance between points , b.

for this, think can either utilize annotate , figure out how supply start , end positions of arrow. or, utilize arrow , label point.

i tried utilize latter, can't figure out how 2-headed arrow:

from pylab import * in [0, 1]: j in [0, 1]: plot(i, j, 'rx') axis([-1, 2, -1, 2]) arrow(0.1, 0, 0, 1, length_includes_head=true, head_width=.03) # draws 1-headed arrow show()

how create 2-headed arrow? improve still, there (simpler) way of marking dimensions in matplotlib figures?

you can alter style of arrow using arrowstyle property, example

ax.annotate(..., arrowprops=dict(arrowstyle='<->'))

gives double headed arrow.

a finish illustration can found here 3rd way downwards page possible different styles.

as 'better' way of marking dimensions on plots cannot think of off top of head.

edit: here's finish illustration can utilize if it's helpful

import matplotlib.pyplot plt import numpy np def annotate_dim(ax,xyfrom,xyto,text=none): if text none: text = str(np.sqrt( (xyfrom[0]-xyto[0])**2 + (xyfrom[1]-xyto[1])**2 )) ax.annotate("",xyfrom,xyto,arrowprops=dict(arrowstyle='<->')) ax.text((xyto[0]+xyfrom[0])/2,(xyto[1]+xyfrom[1])/2,text,fontsize=16) x = np.linspace(0,2*np.pi,100) plt.plot(x,np.sin(x)) annotate_dim(plt.gca(),[0,0],[np.pi,0],'$\pi$') plt.show()

python matplotlib

spotify - Auth missing in Preview API -



spotify - Auth missing in Preview API -

i'd able connect facebook app within spotify (coke highlights allows this).

however, in preview api (which need app) looks authenticatewithfacebook missing:

http://developer.spotify.com/technologies/apps/docs/09321954e7.html

the closest is:

https://developer.spotify.com/technologies/apps/docs/preview/api/api-facebook-facebooksession.html

where can utilize showconnectui, doesn't appear work , undocumented.

the auth module not nowadays @ first, part of spotify apps api. can read more on its documentation page. looks this:

class="lang-js prettyprint-override"> require(['$api/auth#auth'], function(auth) { var appid = '<your_app_id>', permissions = ['user_about_me']; var auth = new auth(); auth.authenticatewithfacebook(appid, permissions) .done(function(params) { if (params.accesstoken) { console.log('your access token: ' + params.accesstoken); } else { console.log('no access token returned'); } }).fail(function(req, error) { console.error('the auth request failed error: ' + error); }); } });

in addition, there a working example in tutorial app on github.

spotify

Java locking on muliple servers -



Java locking on muliple servers -

i have few seats reserved user. @ time, 1 user can participate in reservation process same seat not reserved multiple users. in java code have used "synchronized" keyword done. works.

however, code deployed on 2 servers, s1 , s2. hypothetically, lets there lastly seat available. 2 users, u1 , u2, want reserve lastly seat. might happen load balancer send user u1 server s1 , user u2 server s2. "local" synchronized still work same way not able block other user while making reservation. create lastly seat reserved both users problem.

so question how can create sure multiple users reserve seat without conflict in multiple server environment?

there 4 ways distributed systems can communicate:

shared database. remote procedure calls messaging. shared file-system.

consider shared database approach. . if don't need massive scaling, easiest utilize relational database since of them provide grade of acid (atomocity, consistency, isolation & durability). . .

you can set transaction, , rollback/handle in case of collision - called optimistic locking strategy.

if utilize spring + jpa/hibernate of hard work has been done , need add together @transactional annotation update method. . . great book on spring "spring in action" .

another alternative utilize distributed cache.

java locking synchronized

How can I match nested brackets using regex? -



How can I match nested brackets using regex? -

as title says, here illustration input:

(outer (center (inner) (inner) center) ouer) (outer (inner) ouer) (outer ouer)

of course, matched strings processed recursion.

i want first recursion match:

[ (outer (center (inner) (inner) center) ouer), (outer (inner) ouer), (outer ouer)]

and after processes needless say...

you can utilize regex

(\([^()]*)*(\s*\([^()]*\)\s*)+([^()]*\))*

but match multiple () in single match!but illustration guess there won't problem

regex nested

java - No errors but object via HTTP not working? -



java - No errors but object via HTTP not working? -

follow on before question here. trying send object employee via http. i'm not getting errors hoping printout of employee details @ other end isn't happening. i'm opening log files see printout on tomcat server other indication method has started showing start printout i'm not getting end one. isn't working right in section.

here test class employee:

public class employee implements java.io.serializable { public string name; public string address; public transient int ssn; public int number; public void mailcheck() { system.out.println("mailing check " + name + " " + address); } }

client side:

public class serializeandsend {

public static void main(string args[]){ one.employee e = new one.employee(); e.name = "reyan ali"; e.address = "phokka kuan, ambehta peer"; e.ssn = 11122333; e.number = 101; sendobject(e); } public static object sendobject(object obj) { urlconnection conn = null; object reply = null; seek { // open url connection url url = new url("///myurl///"); conn = url.openconnection(); conn.setdoinput(true); conn.setdooutput(true); conn.setusecaches(false); // send object objectoutputstream objout = new objectoutputstream(conn.getoutputstream()); objout.writeobject(obj); objout.flush(); objout.close(); } grab (ioexception ex) { ex.printstacktrace(); homecoming null; } // recieve reply seek { objectinputstream objin = new objectinputstream(conn.getinputstream()); reply = objin.readobject(); objin.close(); } grab (exception ex) { // ok if exception here // means there no object beingness returned system.out.println("no object returned"); if (!(ex instanceof eofexception)) ex.printstacktrace(); system.err.println("*"); } homecoming reply; }

}

i think thats correct. i'm stuck on server end, have employee class on server side too:

public void dopost(httpservletrequest req, httpservletresponse resp) throws ioexception { system.out.println("start"); object obj; employee emp = null; objectinputstream objin = new objectinputstream(req.getinputstream()); seek { obj = objin.readobject(); } grab (classnotfoundexception e) { e.printstacktrace(); } seek { emp = (employee)objin.readobject(); } grab (classnotfoundexception e) { e.printstacktrace(); } system.out.println("end"); system.out.println(emp.name); }

any ideas whats going wrong on receiving end?

try { obj = objin.readobject(); } grab (classnotfoundexception e) { e.printstacktrace(); } seek { emp = (employee)objin.readobject(); } grab (classnotfoundexception e) { e.printstacktrace(); }

you sending 1 object , trying receive two. either need this:

obj = objin.readobject(); if (obj instanceof employee) { employee emp = (employee)obj; }

or this:

employee emp = (employee)objin.readobject();

not mixture of both. 2 readobject() calls implies reading stream 2 distinct objects, , aren't sending them.

secondly, shouldn't grab exception , utilize instanceof on exception object. in case should have separate catch (eofexception exc), ok if expect receive 0 objects, not otherwise, , grab other possible exceptions separately: not ok.

java http serialization

fancybox - facnybox - close parent from child but keep child open -



fancybox - facnybox - close parent from child but keep child open -

i have searched thoroughly issue on site , google many hours , although cam quite resourceful can not find solution issue, if can done @ all, help in right direction cool!

i have window (main page) , link, opens fancybox (iframe) within window there link open fancybox (iframe) don't want 'frame in frame', looks silly, how can close first frame , maintain kid open?

there several links on 'main page' need this, having urls in script not work (well)

here's mean... www.kamgar.nl

this link in main page , open fancybox...

<a href="/about" class="pop_up" title="about">about</a>

this link in kid (above) , need open (in new fancybox) , close parent (above)

<a href="/message" class="message" title="message">message</a>

and script...

$(document).ready(function() { $(".pop_up").fancybox({ maxwidth : 700, maxheight : 1000, fittoview : false, afterload : function () { $("#content, #page").fadeout(100); }, afterclose : function () { $("#content, #page").fadein(10); }, width : '50%', height : '80%', autosize : false, closeclick : false, openeffect : 'fade', closeeffect : 'fade', scrolloutside: false, padding : '5', hideloading : true, title : false, nextclick : false, type : 'iframe', helpers : { title : { type : 'over'} } }); }); $(document).ready(function() { $(".message").fancybox({ maxwidth : 500, fittoview : false, afterload : function () { $("#content, #page").fadeout(100); }, afterclose : function () { $("#content, #page").fadein(10); }, width : '90%', height : 600, autosize : false, closeclick : false, openeffect : 'fade', closeeffect : 'fade', padding : '5', modal : false, hideloading : true, title : false, nextclick : false, type : 'iframe', helpers : { title : { type : 'over'} } }); });

i have found out since not possible do, found way around triggering hidden link open page beingness opened.

confusing know, page beingness called twice rather once: 1 time page page open 1 time again via fancybox within via hidden link.

if go site think you'll understand.

fancybox fancybox-2

java - Using atomic for generating unique id -



java - Using atomic for generating unique id -

class abc{ private static random random = new random(); private static atomiclong uniquelongid = new atomiclong(system.currenttimemillis()); public static long getuniquelongid(){ long id = uniquelongid.incrementandget(); long uniqueid = math.abs(random.nextlong()) + id; homecoming uniqueid; //the above code can write in 1 line //return math.abs(random.nextlong())+uniquelongid.incrementandget(); } }

will above method getuniquelongid() give me unique id in multithreaded environment. concern here is: knowing uniquelongid atomic , assuming calling incrementandget() thread-safe call, other part of code not synchronized. not mean method getuniquelongid() not thread safe? , may not neccesarily homecoming unique id?

please explain..

the java 7 docs write:

instances of java.util.random threadsafe. however, concurrent utilize of same java.util.random instance across threads may encounter contention , consequent poor performance. consider instead using threadlocalrandom in multithreaded designs.

so code thread safe in java 7. every operation either phone call thread-safe method, or operating on local variables only. , don't require atomicity, i.e. don't require next sequence number paired next random number.

as (per comment) there no such guarantees in older versions of api documentation, implementations in theory non-threadsafe. however, looking @ src.zip in sun jdk 1.4.2.19 (which oldest version have around), code uses atomic variable, providing thread-safe behaviour in practice.

that said, code has number of other problems. quoted above, performance might bad. assylias wrote in comment, approach won't give more unique numbers simple random would. furthermore, math.abs(long.min_value) still negative, , positive random number plus id might cause overflow , wrap-around. if need positive numbers, you'll have add together more care. final uniqueid &= 0x7fffffffffffffffl might more suitable math.abs along way.

java atomic uniqueidentifier java.util.concurrent

c# - 'does not implement interface member 'System.ICloneable.Clone()' -



c# - 'does not implement interface member 'System.ICloneable.Clone()' -

i'm having little issue calling in icloneable interface

i've told class want utilize interface such:

class unitclass: icloneable

and have placed in function cloning

public object clone() { homecoming this.memberwiseclone(); }

however reason programme telling me have not implemented system.icloneable.clone() tried giving function explicit name so...

public object system.icloneable.clone()

but little effect, know i'm doing wrong?

edit: total class

class unitclass: icloneable { //----------------------------------------------------------------------------------------------- //----------------------------------------------variables---------------------------------------- private int unitid; //added xml private string unitname; private int unitbasehp; private int unitcurrenthp; private carrier unitcarrier; private int unitrechargetime; private int turnlastplayed; private int strengthagainstfighters; private int strengthagainstbombers; private int strengthagainstturrets; private int strengthagainstcarriers; //----------------------------------------------------------------------------------------------- //---------------------------------------------constructor--------------------------------------- public unitclass() { unitid = 0; unitname = "name not set"; unitbasehp = 0; unitcurrenthp = 0; unitcarrier = null;//carrier works faction ie red/blue or left/right unitrechargetime = 0; turnlastplayed = 0; strengthagainstfighters = 0; strengthagainstbombers = 0; strengthagainstturrets = 0; strengthagainstcarriers = 0; } //----------------------------------------------------------------------------------------------- //---------------------------------------------gets , sets------------------------------------- public int unitid//public { set { unitid = value; } { homecoming unitid; } } public string unitname//public { set { unitname = value; } { homecoming unitname; } } public int unitbasehp//public { set { unitbasehp = value; } { homecoming unitbasehp; } } public int unitcurrenthp//public { set { unitcurrenthp = value; } { homecoming unitcurrenthp; } } public carrier unitcarrier//public { set { unitcarrier = value; } { homecoming unitcarrier; } } public int unitrechargetime//public { set { unitrechargetime = value; } { homecoming unitrechargetime; } } public int turnlastplayed//public { set { turnlastplayed = value; } { homecoming turnlastplayed; } } public int strengthagainstfighters//public { set { strengthagainstfighters = value; } { homecoming strengthagainstfighters; } } public int strengthagainstbombers//public { set { strengthagainstbombers = value; } { homecoming strengthagainstbombers; } } public int strengthagainstturrets//public { set { strengthagainstturrets = value; } { homecoming strengthagainstturrets; } } public int strengthagainstcarriers//public { set { strengthagainstcarriers = value; } { homecoming strengthagainstcarriers; } } //--------------------------------------------------------------------------- public object clone() { homecoming this.memberwiseclone(); } }

this built fine me.

public class myclone : icloneable { public object clone() { homecoming this.memberwiseclone(); } }

you don't perhaps want share more of class? nil jumping out @ me.

c# icloneable

java - OnActivityResult () -



java - OnActivityResult () -

i have code should allow me take value calculator , utilize further:

//-----------------this section creates keypad functionality (int o = 0; o < keybuttons.length; o++) { final int n = o; keybuttons[o] = (button) findviewbyid(data.keyids[n]); keybuttons[o].setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { seek { string tmp = texts[selectedit].gettext() .tostring(); switch (n) { case 3: texts[selectedit].settext(tmp.substring(0, tmp.length() - 1)); break; //get cursor position , delete char case 7: { // create intent realcalc. intent intent2 = new intent("uk.co.quarticsoftware.realcalc"); double x = 0; // set initial value (double). if (!texts[selectedit].gettext() .tostring() .equals("")) { x = double.valueof(texts[selectedit].gettext() .tostring()); } intent2.putextra("x", x); // launch calculator seek { startactivityforresult(intent2, 0); } grab (activitynotfoundexception e) { intent intent = new intent(intent.action_view, uri.parse("market://details?id=uk.co.nickfines.realcalc")); seek { startactivity(intent); } grab (activitynotfoundexception f) { // google play store app not available. } } break; } //open calculator case 11: { if (!tmp.contains("e")) texts[selectedit].settext(tmp + "" + keybuttons[n].gettext()); break; } //check e if dont have default case case 15: { tl.setvisibility(view.gone); break; } //simulate button default: { texts[selectedit].settext(tmp + "" + keybuttons[n].gettext()); //get cursor start , end , entire string // replace selected string button text //insert break; } } //end of switch } //end of seek grab (activitynotfoundexception e) { intent intent = new intent(intent.action_view, uri.parse("market://details?id=uk.co.nickfines.realcalc")); // calculator not installed } //calculator.num=n; grab (exception e) { stringwriter sw = new stringwriter(); e.printstacktrace(new printwriter(sw)); easyphysactivity.error = sw.tostring(); } } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); if (resultcode == activity.result_ok) { // user pressed ok. double value = data.getdoubleextra("x", double.nan); if (double.isnan(value)) { // calculation result "error". } else { // calculation result ok. } } else { // user pressed cancel or button. } } }); } //----------------------------------------

but doesn't these 3 lines:

@override protected void onactivityresult (int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data);

if delete @override becomes better, still shows error

super.onactivityresult(requestcode, resultcode, data);

what going wrong in here?

you cannot override onactivityresult within onclicklistener because not exist in base of operations class. move onactivityresult code within activity class, not onclicklistner.

java android methods

zend framework2 - Best way to use ServiceManager in Model Class? -



zend framework2 - Best way to use ServiceManager in Model Class? -

i'm trying utilize service manager on entity class don't know best way that.

it's easy on controller because can phone call service manager : $this->getservicelocator();

but, in entity class, if implements servicelocatorawareinterface can retieve servicemanager because entity class isn't phone call service manager :

so best way :

1 - pass servicemanager in entity class controller 2 - using servicemanager build entity class 3 - ... ?

to best understand problem, that's code doesn't work :

my entity class:

class demande extends arrayserializable implements inputfilterawareinterface { /../ public function getusertable() { if (! $this->usertable) { $sm = $this->getservicelocator();//<== doesn't work ! $this->usertable = $sm->get ( 'application\model\usertable' ); } homecoming $this->usertable; }

i wouldn't inject servicemanager model (although can). rather servicemanager build model you, , inject need straight model.

service config:

'factories' => array( 'somethinghere' => function($sm) { $model= new \my\model\something(); homecoming $model; }, '\my\model\demande' => function($sm) { $model= new \my\model\demande(); /** * here utilize sm inject dependencies need * model / service ever.. */ $model->setsomething($sm->get('somethinghere')); homecoming $model; }, /** * alternatively can provide class implementing * zend\servicemanager\factoryinterface * provide instance instad of using closures */ '\my\model\demandedefault' => '\my\model\demandefactory',

place of dependencies within service manager config, , utilize inject dependencies models, services etc you.

an illustration mill class if want utilize mill method rather closures:

demandefactory.php

use zend\servicemanager\factoryinterface; utilize zend\servicemanager\servicelocatorinterface; class demandefactory implements factoryinterface { /** * create new instance * * @param servicelocatorinterface $servicelocator * @return demande */ public function createservice(servicelocatorinterface $servicelocator) { $config = $servicelocator->get('config'); // if need config.. // inject dependencies via contrustor $model = new \my\model\demande($servicelocator->get('somethinghere')); // or using setter if wish. //$model->setsomething($servicelocator->get('somethinghere')); homecoming $model; } }

an illustration model trying instantiate via service manager.

demande.php

class demande { protected $_something; /** * can optionally inject dependancies via constructor */ public function __construct($something) { $this->setsomething($something); } /** * inject dependencies via setters */ public function setsomething($something) { $this->_something = $something; } // injected service manager // there's no need inject sm itself. }

in controller:

public function getdemande() { if (! $this->_demande) { $sm = $this->getservicelocator(); $this->_demande = $sm->get ('\my\model\demande'); } homecoming $this->_demande; }

you inject sergicemanager/servicelocator models models depend on servicelocator.

zend-framework2

How do I find documents containing digits and dollar signs in Solr? -



How do I find documents containing digits and dollar signs in Solr? -

in solr, i've got text contains $30 , 30.

i search $30 , find documents containing $30.

but if searches 30, should find both documents containing $30 , containing 30.

here field type i'm using index text field:

<!-- text_en_splitting, add-on of reversed tokens leading wildcard matches --> <fieldtype name="text_en_splitting_reversed" class="solr.textfield" positionincrementgap="100" autogeneratephrasequeries="true"> <analyzer type="index"> <tokenizer class="solr.whitespacetokenizerfactory"/> <!-- in example, utilize synonyms @ query time <filter class="solr.synonymfilterfactory" synonyms="index_synonyms.txt" ignorecase="true" expand="false"/> --> <!-- case insensitive stop word removal. add together enablepositionincrements=true in both index , query analyzers leave 'gap' more accurate phrase queries. --> <filter class="solr.stopfilterfactory" ignorecase="true" words="lang/stopwords_en.txt" enablepositionincrements="true" /> <filter class="solr.worddelimiterfilterfactory" generatewordparts="1" generatenumberparts="1" catenatewords="1" catenatenumbers="1" catenateall="0" splitoncasechange="1" types="word-delim-types.txt" /> <filter class="solr.lowercasefilterfactory"/> <filter class="solr.keywordmarkerfilterfactory" protected="protwords.txt"/> <filter class="solr.porterstemfilterfactory"/> <filter class="solr.reversedwildcardfilterfactory" withoriginal="true" maxposasterisk="3" maxposquestion="2" maxfractionasterisk="0.33"/> </analyzer> <analyzer type="query"> <tokenizer class="solr.whitespacetokenizerfactory"/> <filter class="solr.synonymfilterfactory" synonyms="synonyms.txt" ignorecase="true" expand="true"/> <filter class="solr.stopfilterfactory" ignorecase="true" words="lang/stopwords_en.txt" enablepositionincrements="true" /> <filter class="solr.worddelimiterfilterfactory" generatewordparts="1" generatenumberparts="1" catenatewords="0" catenatenumbers="0" catenateall="0" splitoncasechange="1" types="word-delim-types.txt" /> <filter class="solr.lowercasefilterfactory"/> <filter class="solr.keywordmarkerfilterfactory" protected="protwords.txt"/> <filter class="solr.porterstemfilterfactory"/> </analyzer> </fieldtype>

i have defined word-delim-types.txt contain:

$ => digit % => digit . => digit

so when search $30, correctly locates documents containing "$30" not containing "30". that's good. when search "30" not find documents containing "$30", containing "30".

is there way this?

i have found solution question. instead of defining $ % , . digit, define them alpha, in "types" file passed in attribute worddelimiterfilterfactory.

$ => alpha % => alpha . => alpha

due rest of worddelimiterfilterfactory settings, things broken , catenated in way desired effect achieved:

searching $30 yields documents containing $30. searching 30 yields documents containing both $30 , 30.

solr

android - Issues with tabactivity and mainactivity using service -



android - Issues with tabactivity and mainactivity using service -

hi have app aacplayer im trying implement tab menu achieved issue here when app opens have run mainactivity.java 1 have service of sound added anothers tabs , works perfect ones doesnt utilize services.

here log of error:

02-14 19:24:11.685: e/androidruntime(31027): java.lang.runtimeexception: error receiving broadcast intent { act=started flg=0x10 } in com.webcraftbd.radio.mainactivity$radioupdatereceiver@42e09468

tabactivity.java:

public class androidtablayoutactivity extends tabactivity { /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); tabhost tabhost = gettabhost(); // tab photos tabspec photospec = tabhost.newtabspec("en vivo"); photospec.setindicator("en vivo", getresources().getdrawable(r.drawable.icon_songs_tab)); intent photosintent = new intent(this, mainactivity.class); photospec.setcontent(photosintent); // tab songs tabspec songspec = tabhost.newtabspec("twitter"); // setting title , icon tab songspec.setindicator("twitter", getresources().getdrawable(r.drawable.icon_photos_tab)); intent songsintent = new intent(this, songsactivity.class); songspec.setcontent(songsintent); // tab videos tabspec videospec = tabhost.newtabspec("contactenos"); videospec.setindicator("contactenos", getresources().getdrawable(r.drawable.icon_videos_tab)); intent videosintent = new intent(this, videosactivity.class); videospec.setcontent(videosintent); // adding tabspec tabhost tabhost.addtab(photospec); // adding photos tab tabhost.addtab(songspec); // adding songs tab tabhost.addtab(videospec); // adding videos tab for(int i=0;i<tabhost.gettabwidget().getchildcount();i++) { textview tv = (textview) tabhost.gettabwidget().getchildat(i).findviewbyid(android.r.id.title); tv.settextcolor(color.white); tv.setpadding(0, 0, 0, 5); tv.setshadowlayer(2, 2, 2, color.black); } } }

mainactivity.java:

public class mainactivity extends baseactivity{ private static boolean displayad; private button playbutton; private button pausebutton; private button stopbutton; private button nextbutton; private button previousbutton; private imageview stationimageview; private textview albumtextview; private textview artisttextview; private textview tracktextview; private textview statustextview; private textview timetextview; private intent bindintent; private telephonymanager telephonymanager; private boolean wasplayingbeforephonecall = false; private radioupdatereceiver radioupdatereceiver; private radioservice radioservice; private adview adview; private string status_buffering; private static final string type_aac = "aac"; private static final string type_mp3 = "mp3"; private seekbar volumeseekbar = null; private audiomanager audiomanager = null; private handler handler; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setvolumecontrolstream(audiomanager.stream_music); setcontentview(r.layout.activity_main); initcontrols(); // bind service seek { bindintent = new intent(this, radioservice.class); bindservice(bindintent, radioconnection, context.bind_auto_create); } catch(exception e) { } telephonymanager = (telephonymanager) getsystemservice(telephony_service); if(telephonymanager != null) { telephonymanager.listen(phonestatelistener, phonestatelistener.listen_call_state); } handler = new handler(); initialize(); } private void initcontrols() { seek { volumeseekbar = (seekbar) findviewbyid(r.id.seekbar1); audiomanager = (audiomanager) getsystemservice(context.audio_service); volumeseekbar.setmax(audiomanager .getstreammaxvolume(audiomanager.stream_music)); volumeseekbar.setprogress(audiomanager .getstreamvolume(audiomanager.stream_music)); volumeseekbar .setonseekbarchangelistener(new onseekbarchangelistener() { @override public void onstoptrackingtouch(seekbar arg0) { } @override public void onstarttrackingtouch(seekbar arg0) { } @override public void onprogresschanged(seekbar arg0, int progress, boolean arg2) { audiomanager.setstreamvolume( audiomanager.stream_music, progress, 0); } }); } grab (exception e) { e.printstacktrace(); } } @override public boolean onkeydown(int keycode, keyevent event) { if (keycode == keyevent.keycode_volume_up) { int index = volumeseekbar.getprogress(); volumeseekbar.setprogress(index + 1); homecoming false; } else if (keycode == keyevent.keycode_volume_down) { int index = volumeseekbar.getprogress(); volumeseekbar.setprogress(index - 1); homecoming false; } homecoming super.onkeydown(keycode, event); } @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); if (newconfig.orientation == configuration.orientation_portrait || newconfig.orientation == configuration.orientation_landscape) { setcontentview(r.layout.activity_main); seek { handler.post( new runnable() { public void run() { initialize(); if(radioservice.gettotalstationnumber()<=1) { nextbutton.setenabled(false); nextbutton.setvisibility(view.invisible); previousbutton.setenabled(false); previousbutton.setvisibility(view.invisible); } updatestatus(); updatemetadata(); //updatealbum(); system.out.println("radioservice.ispreparingstarted() = "+radioservice.ispreparingstarted()); } }); } catch(exception e) { e.printstacktrace(); } } } public void initialize() { seek { displayad = (boolean) boolean.parseboolean(getresources().getstring(r.string.is_display_ad)); status_buffering = getresources().getstring(r.string.status_buffering); playbutton = (button) this.findviewbyid(r.id.playbutton); pausebutton = (button) this.findviewbyid(r.id.pausebutton); stopbutton = (button) this.findviewbyid(r.id.stopbutton); nextbutton = (button) this.findviewbyid(r.id.nextbutton); previousbutton = (button) this.findviewbyid(r.id.previousbutton); pausebutton.setenabled(false); pausebutton.setvisibility(view.invisible); stationimageview = (imageview) findviewbyid(r.id.stationimageview); playbutton.setenabled(true); stopbutton.setenabled(false); albumtextview = (textview) this.findviewbyid(r.id.albumtextview); artisttextview = (textview) this.findviewbyid(r.id.artisttextview); tracktextview = (textview) this.findviewbyid(r.id.tracktextview); statustextview = (textview) this.findviewbyid(r.id.statustextview); timetextview = (textview) this.findviewbyid(r.id.timetextview); startservice(new intent(this, radioservice.class)); displayad(); } grab (exception e) { e.printstacktrace(); } } public void displayad() { if(displayad==true) { // create adview seek { if (adview != null) { adview.destroy(); } adview = new adview(this, adsize.smart_banner, this.getstring(r.string.admob_publisher_id)); linearlayout layout = (linearlayout)findviewbyid(r.id.adlayout); layout.addview(adview); adview.loadad(new adrequest()); } grab (outofmemoryerror e) { e.printstacktrace(); } grab (exception e) { e.printstacktrace(); } } else { linearlayout layout = (linearlayout)findviewbyid(r.id.adlayout); layout.setlayoutparams(new linearlayout.layoutparams(0,0)); layout.setvisibility(view.invisible); } } public void updateplaytimer() { timetextview.settext(radioservice.getplayingtime()); final handler handler = new handler(); timer timer = new timer(); timertask doasynchronoustask = new timertask() { @override public void run() { handler.post(new runnable() { public void run() { timetextview.settext(radioservice.getplayingtime()); } }); } }; timer.schedule(doasynchronoustask, 0, 1000); } public void onclickplaybutton(view view) { radioservice.play(); } public void onclickpausebutton(view view) { radioservice.pause(); } public void onclickstopbutton(view view) { radioservice.stop(); //resetmetadata(); //updatedefaultcoverimage(); } public void onclicknextbutton(view view) { resetmetadata(); playnextstation(); //updatedefaultcoverimage(); } public void onclickpreviousbutton(view view) { resetmetadata(); playpreviousstation(); //updatedefaultcoverimage(); } public void playnextstation() { radioservice.stop(); radioservice.setnextstation(); /* if(radioservice.isplaying()) { radioservice.setstatus(status_buffering); updatestatus(); radioservice.stop(); radioservice.play(); } else { radioservice.stop(); } */ } public void playpreviousstation() { radioservice.stop(); radioservice.setpreviousstation(); /* if(radioservice.isplaying()) { radioservice.setstatus(status_buffering); updatestatus(); radioservice.stop(); radioservice.play(); } else { radioservice.stop(); } */ } public void updatedefaultcoverimage() { string mdrawablename = "station_"+(radioservice.getcurrentstationid()+1); int resid = getresources().getidentifier(mdrawablename , "drawable", getpackagename()); stationimageview.setimageresource(resid); albumtextview.settext(""); } public void updatealbum() { string album = radioservice.getalbum(); string artist = radioservice.getartist(); string track = radioservice.gettrack(); bitmap albumcover = radioservice.getalbumcover(); albumtextview.settext(album); if(albumcover==null || (artist.equals("") && track.equals(""))) updatedefaultcoverimage(); else { stationimageview.setimagebitmap(albumcover); radioservice.setalbum(lastfmcover.album); if(radioservice.getalbum().length() + radioservice.getartist().length()>50) { albumtextview.settext(""); } } } public void updatemetadata() { string artist = radioservice.getartist(); string track = radioservice.gettrack(); //if(artist.length()>30) //artist = artist.substring(0, 30)+"..."; artisttextview.settext(artist); tracktextview.settext(track); albumtextview.settext(""); } public void resetmetadata() { radioservice.resetmetadata(); artisttextview.settext(""); albumtextview.settext(""); tracktextview.settext(""); } @override public void ondestroy() { super.ondestroy(); if(radioservice!=null) { if(!radioservice.isplaying() && !radioservice.ispreparingstarted()) { //radioservice.stopself(); radioservice.stopservice(bindintent); } } if (adview != null) { adview.destroy(); } if(telephonymanager != null) { telephonymanager.listen(phonestatelistener, phonestatelistener.listen_none); } } @override protected void onpause() { super.onpause(); if (radioupdatereceiver != null) unregisterreceiver(radioupdatereceiver); } @override protected void onresume() { super.onresume(); /* register receiving broadcast messages */ if (radioupdatereceiver == null) radioupdatereceiver = new radioupdatereceiver(); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_created)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_destroyed)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_started)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_start_preparing)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_prepared)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_playing)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_paused)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_stopped)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_completed)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_error)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_buffering_start)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_buffering_end)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_metadata_updated)); registerreceiver(radioupdatereceiver, new intentfilter(radioservice.mode_album_updated)); if(wasplayingbeforephonecall) { radioservice.play(); wasplayingbeforephonecall = false; } } /* receive broadcast messages radioservice */ private class radioupdatereceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(radioservice.mode_created)) { } else if (intent.getaction().equals(radioservice.mode_destroyed)) { playbutton.setenabled(true); pausebutton.setenabled(false); stopbutton.setenabled(false); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); //updatedefaultcoverimage(); updatemetadata(); updatestatus(); } else if (intent.getaction().equals(radioservice.mode_started)) { pausebutton.setenabled(false); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); playbutton.setenabled(true); stopbutton.setenabled(false); updatestatus(); } else if (intent.getaction().equals(radioservice.mode_start_preparing)) { pausebutton.setenabled(false); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); playbutton.setenabled(false); stopbutton.setenabled(true); updatestatus(); } else if (intent.getaction().equals(radioservice.mode_prepared)) { playbutton.setenabled(true); pausebutton.setenabled(false); stopbutton.setenabled(false); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); updatestatus(); } else if (intent.getaction().equals(radioservice.mode_buffering_start)) { updatestatus(); } else if (intent.getaction().equals(radioservice.mode_buffering_end)) { updatestatus(); } else if (intent.getaction().equals(radioservice.mode_playing)) { if(radioservice.getcurrentstationtype().equals(type_aac)) { playbutton.setenabled(false); stopbutton.setenabled(true); } else { playbutton.setenabled(false); pausebutton.setenabled(true); stopbutton.setenabled(true); playbutton.setvisibility(view.invisible); pausebutton.setvisibility(view.visible); } updatestatus(); } else if(intent.getaction().equals(radioservice.mode_paused)) { playbutton.setenabled(true); pausebutton.setenabled(false); stopbutton.setenabled(true); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); updatestatus(); } else if(intent.getaction().equals(radioservice.mode_stopped)) { playbutton.setenabled(true); pausebutton.setenabled(false); stopbutton.setenabled(false); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); updatestatus(); } else if(intent.getaction().equals(radioservice.mode_completed)) { playbutton.setenabled(true); pausebutton.setenabled(false); stopbutton.setenabled(false); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); updatestatus(); } else if(intent.getaction().equals(radioservice.mode_error)) { playbutton.setenabled(true); pausebutton.setenabled(false); stopbutton.setenabled(false); playbutton.setvisibility(view.visible); pausebutton.setvisibility(view.invisible); updatestatus(); } else if(intent.getaction().equals(radioservice.mode_metadata_updated)) { updatemetadata(); updatestatus(); //updatedefaultcoverimage(); } else if(intent.getaction().equals(radioservice.mode_album_updated)) { //updatealbum(); } } } phonestatelistener phonestatelistener = new phonestatelistener() { @override public void oncallstatechanged(int state, string incomingnumber) { if (state == telephonymanager.call_state_ringing) { wasplayingbeforephonecall = radioservice.isplaying(); radioservice.stop(); } else if(state == telephonymanager.call_state_idle) { if(wasplayingbeforephonecall) { radioservice.play(); } } else if(state == telephonymanager.call_state_offhook) { //a phone call dialing, active or on hold wasplayingbeforephonecall = radioservice.isplaying(); radioservice.stop(); } super.oncallstatechanged(state, incomingnumber); } }; public void updatestatus() { string status = radioservice.getstatus(); if(radioservice.gettotalstationnumber() > 1) { if(status!="") status = radioservice.getcurrentstationname()+" - "+status; else status = radioservice.getcurrentstationname(); } seek { statustextview.settext(status); } catch(exception e) { e.printstacktrace(); } } // handles connection between service , activity private serviceconnection radioconnection = new serviceconnection() { public void onserviceconnected(componentname classname, ibinder service) { radioservice = ((radioservice.radiobinder)service).getservice(); if(radioservice.gettotalstationnumber()<=1) { nextbutton.setenabled(false); nextbutton.setvisibility(view.invisible); previousbutton.setenabled(false); previousbutton.setvisibility(view.invisible); } updatestatus(); updatemetadata(); //updatealbum(); updateplaytimer(); radioservice.shownotification(); //radioservice.play(); } public void onservicedisconnected(componentname classname) { radioservice = null; } }; }

baseactivity.java:

public class baseactivity extends activity { private intent bindintent; private radioservice radioservice; private static boolean isexitmenuclicked; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); isexitmenuclicked = false; // bind service bindintent = new intent(this, radioservice.class); bindservice(bindintent, radioconnection, context.bind_auto_create); setvolumecontrolstream(audiomanager.stream_music); } @override protected void onresume() { super.onresume(); if(isexitmenuclicked==true) finish(); } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main_menu, menu); homecoming true; } @override public boolean onoptionsitemselected(menuitem item) { intent i; final string thisclassname = this.getclass().getname(); final string thispackagename = this.getpackagename(); switch (item.getitemid()) { case r.id.radio: if(!thisclassname.equals(thispackagename+".mainactivity")) { = new intent(this, mainactivity.class); i.addflags(intent.flag_activity_clear_top); i.addflags(intent.flag_activity_new_task); startactivity(i); homecoming true; } break; case r.id.facebook: if(!thisclassname.equals(thispackagename+".facebookactivity")) { = new intent(this, facebookactivity.class); startactivity(i); homecoming true; } break; case r.id.twitter: if(!thisclassname.equals(thispackagename+".twitteractivity")) { = new intent(this, twitteractivity.class); startactivity(i); homecoming true; } break; case r.id.about: if(!thisclassname.equals(thispackagename+".aboutactivity")) { = new intent(this, aboutactivity.class); startactivity(i); homecoming true; } break; case r.id.exit: string title = "exit radio"; string message = "desea salir de la aplicacion?"; string buttonyesstring = "si"; string buttonnostring = "no"; isexitmenuclicked = true; alertdialog.builder advertisement = new alertdialog.builder(this); //ad.settitle(title); ad.setmessage(message); ad.setcancelable(true); ad.setpositivebutton(buttonyesstring, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { if(radioservice!=null) { radioservice.exitnotification(); radioservice.stop(); radioservice.stopservice(bindintent); isexitmenuclicked = true; finish(); } } }); ad.setnegativebutton(buttonnostring, null); ad.show(); homecoming true; } homecoming super.onoptionsitemselected(item); } // handles connection between service , activity private serviceconnection radioconnection = new serviceconnection() { public void onserviceconnected(componentname classname, ibinder service) { radioservice = ((radioservice.radiobinder)service).getservice(); } public void onservicedisconnected(componentname classname) { radioservice = null; } }; }

i dont know else can prepare main activity.

thank much.

bindservice(bindintent, radioconnection, context.bind_auto_create);

in mainactivity.java, code must below;

getapplicationcontext().bindservice(bindintent, radioconnection, context.bind_auto_create);

android android-layout android-tabhost android-service android-tabactivity

nfc - How can I read (and write) Mifare DesFire Cards with Android -



nfc - How can I read (and write) Mifare DesFire Cards with Android -

i'm trying read , write android app mifare desfire card (classic works already) don't know how works :). know has transceive(byte[]) responsible communicating through raw bytes how work in detail? can give me code-snippets?

thanks lot , best regards.

it rather complicated that, because communication ciphered , cmac. i've found high level sdk job don't have deal transceive , that, private message me if interested..

android nfc rfid mifare

java - Kill a process started by exec() after some duration and store frames in an array -



java - Kill a process started by exec() after some duration and store frames in an array -

let me start off saying i'm new java. i'm php background, happens 1 of php tasks need converted java.

the task splitting video frames using ffmpeg , working frames. i've completed process in php. , can convert java.

i went on tutorials , have got bases covered (using ide, running java programme etc). i'm using eclipse purpose.

i've far managed start ffmpeg withing java programme using

public static void main(string[] args) throws ioexception { string livestream = "d:/video.mpg"; string folderpth = "d:/frames"; string cmd="d:/ffmpeg/bin/ffmpeg.exe -i "+ livestream +" -r 10 "+folderpth+"/image%d.jpg"; //system.out.println(cmd); runtime r = runtime.getruntime(); process p = r.exec(cmd); // starts creating frames // , stores them on local disk // way store frame name in array? // string[] frames = {"image%d.jpg"} // frames array contains image1.jpg, image2.jpg..and on? }

this working fine, i'm getting frames in folder. want kill process after some, 5 minutes, video on 2 hours long , don't want have go taskbar , kill process manually. know if there way store frame names created ffmpeg array future use.

i tried using p.destroy() didn't stop process @ all. how go using similar settimeout() used in jquery?

some metadata

os : windows 7

ide : eclipse

p.destroy() sends kill pid on linux. means process receives signal not terminates. have execute kill -9 pid sure process indeed terminated. unfortunately standard java api not provide such functionality, have yourself.

but not complicated. there 2 commands: kill unix , killtask windows. both take process id. can find reflection: private int filed pid presents in platform specific subclass of process instance of runtime.exec()

edit

on linux runtime.exec() returns instance of unixprocess extends process. not have windows available , cannot check far remember on windows returns instance of windowsprocess or that. both have private int field pid can extracted using reflection:

process proc = rutime.getruntime().exec("my command"); field f = proc.getclass().getdeclaredfield("pid"); f.setaccessible(true); int pid = (integer)f.get(proc);

java ffmpeg exec

c# - is Process.Start() synchronous? -



c# - is Process.Start() synchronous? -

i have code this:

processstartinfo psi= new processstartinfo(...); process process = process.start(psi); application.current.shutdown();

even process have process info of application (i have logs) in rare cases on production computer process not opened @ all.

as process.start() synchronous , if returns value there must running process.

another info have genuine process shell process.

does have thought problem?

process io artifact, there delays, between start , opened.

this delay, naturally, depends on concrete machine, run code.

so, solution can

or sleep main thread untill p process opened, amount of time

or close main thread, when (say) timer able find required p process in list of run os processes.

the second, think, improve solution.

c# asynchronous process

How do I transform an XML element name into an attribute value using XSLT? -



How do I transform an XML element name into an attribute value using XSLT? -

given xml snippet:

<transactions> <tran id="1"> <e8> <datestamp>2012-05-17t15:16:57z</datestamp> </e8> </tran> </transactions>

how transform element <e8> <event type="e8"> using xslt?

edit: expected output:

<transactions> <tran id="1"> <event type="e8"> <datestamp>2012-05-17t15:16:57z</datestamp> </event> </tran> </transactions>

use:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <xsl:template match="tran/*"> <event type="{name()}"> <xsl:value-of select="."/> </event> </xsl:template> </xsl:stylesheet>

output:

<transactions> <tran id="1"> <event type="e8">2012-05-17t15:16:57z</event> </tran> </transactions>

xml xslt xpath

java - Json object is not returned from XAMPP server -



java - Json object is not returned from XAMPP server -

i got andoird application, want result returned android textview. test on browser , yes result showed homecoming nil android application.

following code php file.

<?php $accounts = mysql_connect("localhost","user123","1234") or die (mysql_error()); mysql_select_db("user123",$accounts); if(isset($_get["id"])){ $id = $_get['id']; $result = mysql_query("select * table123 id = $id"); if($result != null){ $result = mysql_fetch_array($result); $user = array(); $user["username"] = $result["username"]; $user["password"] = $result["password"]; echo json_encode($user); }else{ } }else{ $user["username"] = "not found"; $user["password"] = null; echo json_encode($user); } ?>

following code browser result

{"username":"not found","password":null}

even result not found, should homecoming $user show me "not found". it's impossible nil returned stream. have test on browser , yes returned $user me. wrong code?

replace "localhost" "10.0.2.2"

and add together line manifest:

<uses-permission android:name="android.permission.internet" />

if utilize android 3.0 or higher (in case do). alter emulator 2.3.3 if possible, seek run code again. or add together these lines code:

strictmode.threadpolicy policy = new strictmode.threadpolicy.builder().permitall().build(); strictmode.setthreadpolicy(policy);

java php android json parsing

sql - MySQL Join Update -



sql - MySQL Join Update -

a (supposedly) simple update has turned out not simple. no matter syntax seek other answered questions, same response mysql:

0 row(s) affected rows matched: 124 changed: 0 warnings: 0

try 1:

update news_content, news_map set news_content.active='no' news_content.rowid = news_map.newsid , news_map.catid = 170;

try 2:

update news_content left bring together news_map on news_map.newsid = news_content.rowid set news_content.active = 'no' news_map.catid = 170;

try 3:

update news_content nc bring together news_map nm on nm.newsid = nc.rowid , nm.catid = 170 set nc.active = 'no';

what think work?

might silly question news_content.active equal 'no'?

mysql sql join

sql server - Losing leading 0 from stored procedure -



sql server - Losing leading 0 from stored procedure -

i trying right zip code city , state values. losing leading 0s zip code.

example

create procedure sp_getcorrectvalue begin declare @value nvarchar(5) set @value = '00254' homecoming @value end declare @getvalue nvarchar(5) exec @getvalue = sp_getcorrectvalue select @getvalue zipcode

it should homecoming 00254, returns 254 not correct

please help thanks

you should create function

create function fn_getcorrectvalue() returns nvarchar(5) begin declare @value nvarchar(5) set @value = '00254' homecoming @value end

demo @ http://sqlfiddle.com/#!3/29fa9/1/0

stored procedures homecoming integer (http://msdn.microsoft.com/en-us/library/ms174998.aspx)

stored procedures can homecoming integer value calling procedure or application

sql-server sql-server-2008

iphone - How to compare an array of NSStrings containing Dates in ascending order -



iphone - How to compare an array of NSStrings containing Dates in ascending order -

i have array in contains list of dates represented strings:

nsmutablearray *objarray=[[nsmutablearray alloc]init]; [objarray addobject:@"18-01-2013 2:51"]; [objarray addobject:@"16-01-2013 5:31"]; [objarray addobject:@"15-01-2013 3:51"]; [objarray addobject:@"17-01-2013 4:41"]; [objarray addobject:@"03-02-2013 3:21"]; [objarray addobject:@"05-01-2013 3:01"];

please tell me how arrange array in ascending order using dates.

nsdateformatter *formatter = [[[nsdateformatter alloc] init] autorelease]; [formatter setdateformat:@"dd-mm-yyyy hh:mm"];

nscomparator comparedates = ^(id string1, id string2) { nsdate *date1 = [formatter datefromstring:string1]; nsdate *date2 = [formatter datefromstring:string2]; homecoming [date1 compare:date2]; }; nssortdescriptor * sortdesc = [[[nssortdescriptor alloc] initwithkey:@"self" ascending:no comparator:comparedates]autorelease]; [objarray sortusingdescriptors:[nsarray arraywithobject:sortdesc]];

by using code got exact output, give thanks

iphone ios objective-c nsmutablearray