Posts

Showing posts from September, 2013

Class definition syntax in python -

i new python.i working python code.i trying map python object oriented concepts of c++ think way learn.i can across 2 types of class definitions. class sourcetoport(base): """""" __tablename__ = 'source_to_port' id = column(integer, primary_key=true) port_no = column(integer) src_address = column(string) #---------------------------------------------------------------------- def __init__(self, src_address,port_no): """""" self.src_address = src_address self.port_no = port_no and second one. class tutorial (object): def __init__ (self, connection): print "calling tutorial __init__" self.connection = connection connection.addlisteners(self) self.mac_to_port = {} self.matrix={} i want know difference between base in sourcetoport , object in tutorial? you seem using sqlalchemy in first case. not miss di

mysql - Order of execution of SQL UPDATE while updating multiple values? -

what sequence in values (separated commas) updated? $command = sprintf('update %s set rating = ((rating * rating_count + %f) / (rating_count + 1.0)) , rating_count=rating_count+1 id=%d', $table, $ratinggiven, $id)`; i want make sure that rating = (rating * rating_count + %f) / (rating_count + 1.0) is executed before rating_count=rating_count+1 without firing 2 sql commands. i not sure if update-value-statements executed in order in separated commas in mysql (or other db)? i don't think matter update read current row , update upon based on existing values, , not ones in update. so in both set operations, original value of rating_count used.

php - split a string whilst use left join -

i have 2 databases. first contains list of upload doucuments , when uploaded , expiry date. stored numbers representing each grade of person using implode. column name 'foagrade' has 10,11,12 in row one. second database list of grades , there id's eg 10 = manager, 11 = hr etc. using left join , basic html table display query. $result = mysqli_query($con, "select upload.id, upload.title, upload.faograde,upload.faolocation, upload.date, upload.expiry, grade.id, grade.grade gr, grade.id upload left join grade on upload.faograde=grade.id owner=$user"); echo "<table id='previous'> <tr> <th>title/document name:</th> <th>for attention of grade</th> <th>for location</th> <th>date</th> <th>date expires</th> <th>delete briefing</th> </tr>"; while($row = mysqli_fetch_array($result)) { $id=$row['id']; echo "<tr>"; echo "<

html - how to overlap two div in css? -

Image
i have 2 div likes , <div class="imagediv"></div> <div class="imagediv"></div> and css class , .imagediv { margin-left: 100px; background: #fff; display: block; width: 345px; height: 220px; padding: 10px; border-radius: 2px 2px 2px 2px; -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset; -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset; } you can see result here :) i want overlap 2 div likes , add second div bottomdiv and add css. .bottomdiv{ position:relative; bottom:150px; left:150px; } http://jsfiddle.net/aw8rd/1/

actionscript 3 - Can any one explain this code how i use this in my application -

i have problem similar this question i'm not able understand answer code, can 1 explain code. private function attachlisteners():void { this.addeventlistener(mouseevent.mouse_down, selfmousedownhandler, false,0,true); this.addeventlistener(moveevent.move, selfmovehandler, false,0,true); } private function selfmovehandler(event:moveevent):void { redrawconnectedlinks(); } private function selfmousedownhandler(event:mouseevent):void { stage.addeventlistener(mouseevent.mouse_up, stagemouseuphandler, false,0,true); stage.addeventlistener(mouseevent.mouse_move, stagemousemovehandler, false,0,true); } private function stagemouseuphandler(event:mouseevent):void { stage.removeeventlistener(mouseevent.mouse_up, stagemouseuphandler, false); stage.removeeventlistener(mouseevent.mouse_move, stagemousemovehandler, false); } private function stagemousemovehandler(event:mouseevent):void { dispatchevent(new moveevent(moveevent.move)); } please suggest me

android - Retrieve filename from a web folder -

i using asynctask download file web folder. however, name of file different every time. is there way name of file in web folder? (there 1 file in folder @ given time). http://www.example.com/myfolder/myfile_1 try apacheurllister (i didn't tested may work): url url; list serverdir = null; try { url = new url("http://www.abc.com/myfolder/"); apacheurllister lister = new apacheurllister(); serverdir = lister.listall(url); } catch (exception e) { e.printstacktrace(); log.e("error on getting file","error " +e); } system.out.println(serverdir); return serverdir;

java - ComboBox (setSelectedIndex()) is not working properly -

i have 7 items in combobox , every time when select 1 of them , click "next" button selects first item not next. knows why? if ("Цена (euro)".equals((string) combobox.getselecteditem())) { if (!"".equals(txtarea.gettext().tostring())) { cenaeuroa = null; string data = (string) txtarea.gettext(); string[] temp = data.split("\n"); cenaeuroa = new string[temp.length]; system.arraycopy(temp, 0, cenaeuroa, 0, temp.length); len = cenaeuroa.length; } combobox.setselectedindex(0); // object sort = "СОРТ"; // combobox.setselecteditem(sort); } txtarea.settext(null); you selecting first element, combobox.setselectedindex(0). should use getselectedindex() retrieve selected item , use set next. for example: final int selectedindex = combobox.getselectedindex(

android - Button placed in FrameLayout does not work properly in 2.3.6 device, even though compiled from 2.3.3 (API 10) SDK -

i have installed api level 10 sdk ( aka 2.3.3 ). i've made simple linear arrangement of buttons added programmatically on framelayout. mintargetversion = "8" maxtargetversion = "10" runs on ics 4.0.4 device. runs on simulator. when install apk in devices having os 2.3.5 or 2.3.6, buttons not obey left margin parameters , comes clubbed 1 onto another. i've seen framelayout introduced in api level 1, while running devices @ api level 10 or higher, shouldn't problem. my sample code of adding button button b1 = new button(this); framelayout framelayout = (framelayout)this.findviewbyid(r.id.mainactivityview); framelayout.layoutparams params = framelayout.layoutparams(100,100); //a 100x100 button params.leftmargin = 10; // in other buttons, values incremented 100, 200 params.topmargin = 10; framelayout.addview(b1,params); can let me know causing such improper behaviour? try adding gravity params. params.gravity = gravity.start |

javascript - Is my password generating function inefficient? -

i have javascript password generating function. right i'm discarding passwords don't match selected specifications. example if password doesn't contain numbers, discard , generate new 1 hopping 1 have number in it. doesn't seem efficient performance vise, @ least not me. is there better way implement forcing of specific characters in generated password? also i'm planning add password can forced contain special characters. if current way, have have regex check if password contains special characters , if not throw way (again doesn't seem efficient me). function generatepassword(length, charset, nosimilar) { // default parameters length = (typeof length === "undefined") ? 8 : length; charset = (typeof charset === "undefined") ? 'abcdefghjknpqrstuvwxyzabcdefghjklmnpqrstuvwxyz123456789' : charset; nosimilar = (typeof similar === "undefined") ? true : nosimilar; var gen; retval = "";

php - intl extension php_intl.dll with wamp -

i want use moodle, error during installation process: php_extension->intl->should installed , enabled best results. intl extension used improve internationalization support, such locale aware sorting. when click on link, error message above: http://docs.moodle.org/24/en/admin/environment/php_extension/intl i followed link, still same error. if has ideas, please me out. i had same problem few days ago. you have copy files (all files starts icu* ): icudt.dll icudt46.dll icuin.dll icuin46.dll icuio.dll icuio46.dll icule.dll icule46.dll iculx.dll iculx46.dll icutest.dll icutest46.dll icutu.dll icutu46.dll icuuc.dll icuuc46.dll from: <wamp_installation_path>/bin/php/php5.4.3/ to: <wamp_installation_path>/bin/apache/apache2.2.22/bin/ and need enable intl in php.ini file (uncomment line): ;extension=php_intl.dll and restart server. should works fine. of course, need replace folder names own.

iphone - How to open an encrypted sqlite in terminal -

i created .db3 sqlite file in windows,the problem encrypted it,but couldn't manage open directly in terminal app on mac.i know in xcode,i can use sqlite_key open it,but want modify data directly in terminal app.so want know,is there command in sqlite prompt let me open encrypted sqlite file.

python - Filter pandas DataFrame columns -

i have dataframe this: b c d 2000-01-03 -0.59885 0.18141 -0.68828 0.77572 2000-01-04 0.83935 0.15993 0.95911 -1.12959 2000-01-05 2.80215 -0.10858 -1.62114 -0.20170 2000-01-06 0.71670 -0.26707 1.36029 1.74254 i filter columns based on value of first row. e.g. want take columns first value >0. , result expect this: b d 2000-01-03 0.18141 0.77572 2000-01-04 0.15993 -1.12959 2000-01-05 -0.10858 -0.20170 2000-01-06 -0.26707 1.74254 update jeff suggestion wrote code: cols = [] firstrow = df.ix[0,:] in range(len(firstrow)): if firstrow[i]>0: cols.append(i) return df.ix[:, list(cols)].values.copy() is there more elegant way this? this using data generated below, can apply example. iloc[-2] selects 2nd last row, , creates boolean array loc takes boolean array , select applicable columns in [2]: df = dataframe(np.random.randn(4,4),columns=list('abcd'),

java - In what case it will be not thread-safety -

all, better understanding attributes of httpsession thread issue.i wrote test code ,i had thought below code should thread-safety way go. httpsession session = request.getsession(); synchronized (session) { integer n = (integer) session.getattribute("foo"); session.setattribute("foo", (n == null) ? 1 : n + 1); } but answer of tell me not . can't understand ,in opinion, thought session conversion between 1 client , server .is there thread issue situation? if there , please tell me in case code not thread-safety. thanks. afaik, nothing prevents servlet container return different object each time thread asks session (i.e. proxy on real, actual session). if container that, synchronizing on session won't of help, since each thread synchronize on different object. the easiest way have thread-safe counter use atomicinteger, , call 1 of increment methods, doesn't prevent 2 concurrent threads storing atomicinteger first time if both

ruby - Grouping by one column and summing multiple other columns in Rails -

i'm found ugly way need (currently in rails view, i'll move later), find articles of particular user, group them individual publications, , sum share counts of of articles user has added publication. ...but it's not pretty. if there's better way this, can advise? =@user.articles.group(:publication).map |p| =p.publication =@user.articles.where("publication = ?", p.publication).sum(:twitter_count) =@user.articles.where("publication = ?", p.publication).sum(:facebook_count) =@user.articles.where("publication = ?", p.publication).sum(:linkedin_count) this gives output (e.g.) nyt 12 18 14 bbc 45 46 47 cnn 75 54 78, pretty need. however, @ present, it's outputting stuff on end - "[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] sum(:twitter_count)" - think .map i'm not sure why. change = - in first line. - @user.articles.group(:publication).map |p|

android - Adding multiple functions to a ViewPager -

i new android development , trying create sliding carousel buttons link off other activities, have far... main.java public class mainactivity extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); //remove title bar this.requestwindowfeature(window.feature_no_title); setcontentview(r.layout.activity_main); //sliding carousel controls mypageradapter adapter = new mypageradapter(); viewpager mypager = (viewpager) findviewbyid(r.id.myfivepanelpager); mypager.setadapter(adapter); mypager.setcurrentitem(1); } //sliding carousel controls class mypageradapter extends pageradapter { public int getcount() { return 5; } public object instantiateitem(view collection, int position) { layoutinflater inflater = (layoutinflater) collection.getcontext() .getsystemservice(context.layout_inflater_service); int resid = 0; switch

media player - Error streaming file on android 2.x, working on 4.x -

i wrote class extends android mediaplayer, class following package it.ccevas.ccevasandroid; import java.io.ioexception; import android.media.audiomanager; import android.media.mediaplayer; public class mymediaplayer extends mediaplayer { public mymediaplayer(){ super(); setonpreparedlistener(new onpreparedlistener() { public void onprepared(mediaplayer mp) { start(); } }); setonerrorlistener(new onerrorlistener() { @override public boolean onerror(mediaplayer mp, int what, int extra) { if (what == -38){ return true; } return false; } }); } public boolean changesource (string urlfile){ try{ reset(); setaudiostreamtype(audiomanager.stream_music); setdatasource(urlfile); prepare(); seekto(0); } catch (illegalargumentexception e1) { e1.printstacktrace(); } catch (securityexception

Rails routing send string with dots and int -

i'm new rails... i try send such string :search param: "55.675155, 21.833466" , 2 :id param... bad... i no route matches [get] "/exchanger_lists/get_exchangers_via_coordinates/..... my route file: match 'exchanger_lists/get_exchangers_via_coordinates/:search,:id' => 'exchanger_lists#get_exchangers_via_coordinates' but how url must in browser??? how in rails way? read doc's, not clear on 100% ( just how configure route , how call browser? match 'exchanger_lists/get_exchangers_via_coordinates/:search,:id' => 'exchanger_lists#get_exchangers_via_coordinates', constraints: { search: /[^\/]+/ } from here

javascript - in as function name gives error -

i building phonegap based android application in have created function named in when run application, on console gives below error: syntaxerror: parse error @ file:///android_asset/www/clause.js:59 function clause() { this.in = function() {} } you can use bracket notation set , access reserved words property names. function clause() { this['in'] = function() {} }

php - Elements with common and separate properties in a database -

i have database table post , user can submit many types of posts, , these types share properties, , have properties of own. e.x: both video , standard posts have description , video posts have video link/file property. what did creating table post containing common properties, creationdate , description . and created other tables, containing other properties, , number of post types grows, think have add more tables. of course, problem design when want retrieve 1 post, have retrieve data posts table, use id , type retrieve data type table (ex : videos table). , when want retrieve data of different types in 1 page i'll have handle many tables. which seems not practical since i'm working php/mysql in apache server. is there other better idea can implement same result? your design follows technique described in class-table-inheritance . there outline of technique in info tab. you might want explore using shared-primary-key way speed things up, , way

c++ - How to raise events of backgroundworker -

i using vs2010, c++/clr windowsformsapplication. want raise runworkercomplete event using backgroundworker->onrunworkercomple method backgroundworker1->runworkerasync(); while (progressbar1->value != progressbar1->maximum) { progressbar1->value = parentform1->importeddata[comboboxselecteditemid]->progressstatus; } the thing in backgroundworker1 start time-consuming operation. , while bgw isbusy progressbar cheking value of int variable progressstatus . problem runworkercompleted doesn't raise. how can raise in dowork ? private: system::void backgroundworker1_dowork(system::object^ sender, system::componentmodel::doworkeventargs^ e) { myclassobject->timeconsumingoperation(); //how raise runworkercompleted here??? }

flash - How to add in-app purchases for Android with Adobe AIR -

i'm developing game in flash mobile using adobe air.i want add in-app purchases game,specifically additional style packages people can buy.i tried find information on android developers describes process of managing in-app purchases. question is,how implement adobe air?i've heard of native extensions , stuff don't understand product side: can players download packages spritesheets or can packages included in game beginning activated when buy them? thanks. on android can both: include deactivate or load afterwards. regarding requered ane: try this . pretty list finding several anes

html - Accessing parent object variables from within the scope of the child object in php -

so have been researching templating engines , how create own simple templating engine. pure learning perspective, read through couple of them 1 here . using little modified version of class mentioned in above link, thought of testing out encountered problem. when calling instances of same template class inner html , assigning var/value pair parent instance, i'm unable access main parent's variables within the html (child object). confusing? maybe following code help. so if instanciate template ( template class same 1 mentioned in above link) - $_page = new tplengine(); $_page->load(tplfiles_dir . "/root.php"); and instanciate header.html new instance of tplengine class, , assign variable 1st instance follows - $_header = new tplenginechild(tplfiles_dir . "/common/header.html"); $_page->set("header", $_header->parse()); where... root.php --------------- <!doctype html> <html> <head>

android - Robotium in -no-window Emulator throws Click can not be completed -

i'm using robtium 4.1 when run robotium test on emulator visible can click on button using: final button startbutton = (button) solo.getcurrentactivity().findviewbyid( com.coop.r.id.btn_start); solo.clickonview(startquizbutton); doing same thing in emulator launched invisible -no-window option exception : [info] android.device parameter set emulator [info] emulator-5554_avd_for_galaxy_tab_10_1_unknown_sdk : running instrumentation tests in com.company.abc.app.test [info] emulator-5554_avd_for_galaxy_tab_10_1_unknown_sdk : run started: com.company.abc.app.test, 1 tests: [info] emulator-5554_avd_for_galaxy_tab_10_1_unknown_sdk : failure:com.company.abc.app.singlechoicetest#testapptype [info] emulator-5554_avd_for_galaxy_tab_10_1_unknown_sdk : junit.framework.assertionfailederror: click can not completed! @ com.jayway.android.robotium.solo.clicker.clickonscreen(clicker.java:85) @ com.jayway.android.robotium.solo.clicker.clickonscreen(c

html - JavaScript syntax error (I think) -

i'm working on homework class , copied code straight out of book , it's not working. problem copyright() function isn't displaying. countdown() function being display somewhere else , works perfectly. see i'm doing wrong here? function countdown() { var today = new date() var dayofweek = today.tolocalestring() daylocate = dayofweek.indexof(" ") weekday = dayofweek.substring(0, daylocate) newday = dayofweek.substring(daylocate) datelocate = newday.indexof(",") monthdate = newday.substring(0, datelocate+1) yearlocate = dayofweek.indexof("2013") year = dayofweek.substr(yearlocate, 4) var bridalexpo = new date("february 12, 2014") var daystogo = bridalexpo.gettime()-today.gettime() var daystobridalexpo = math.ceil(daystogo/(1000*60*60*24)) displaycountdown.innerhtml = "<p style='font-size:12pt; font-family: helvetica;'>today " +weekday+"

osx - How to get default shell -

we can run chsh -s /usr/local/bin/zsh set new default shell. there command can run know shell is? i don’t mean having terminal open , running command know shell we’re in, mean in example above, if i’m in terminal /bin/bash open, should run /usr/local/bin/zsh if it’s current default shell? you can use following command echo $shell

php - A form (action) error -

i have question, have page , form direct edit data database. need way use form , redirect action=editcinemas.php?cinema_id=the id of cinema <html> <body> <form name="form3" method="post" action="editcinemas.php"> //my problem here guess <td> <table> <?php require('../classes/cinema_class.php'); $cinema=new cinema($_get["cinema_id"]); $cinemas = $cinema->get_all_cinemas(); foreach ($cinemas $movie) { $cinema_id = $movie['cinema_id']; $cinema_name = $movie['cinema_name']; $cinema_location = $movie['cinema_location']; } echo "<input name='cinemaid' type='hidden' id='cinemaid' value=" . $cinema_id . '><br/>'; echo "cinema name :"; echo "<input name='cinemaname' type='text' id='cinemaname' value=" . $cinema_name . '><br/&g

Ruby on Rails Splitting or Slicing list into columns -

@locations = location.all #current listing @locations = location.slice(5) or location.split(5) with ruby i'm trying split list 4 columns, limiting each column 5 each; neither slicing or splitting seems work. idea of might doing wrong? appreciated. you want use in_groups_of: http://railscasts.com/episodes/28-in-groups-of here's ryan bates' example usage railscast: <table> <% @tasks.in_groups_of(4, false) |row_tasks| %> <tr> <% task in row_tasks %> <td><%= task.name %></td> <% end %> </tr> <% end %> </table>

Change warning messages in php -

change warning messages in php warning: include (tools / test_db / viewposta.php) [function.include]: failed open stream: no such file or directory in d: \ program files \ server xampp \ xampp \ htdocs \ projc \ writecode \ tools \ terminal \ run.php on line 45 warning: include () [function.include]: failed opening 'tools / test_db / viewposta.php' inclusion (include_path = '.; d: \ program files \ server xampp \ xampp \ php \ pear') in d: \ program files \ server xampp \ xampp \ htdocs \ projc \ writecode \ tools \ terminal \ run.php on line 45 be error @ \projc\writecode\tools\terminal\run.php on line 45. if within class, recommend looking @ set_error_handler here . set_error_handler( function($level,$msg,$file,$line) { echo "error @ ".$file." on line ".$line; exit; } );

search - Wordpress custom fields content don't appear when searched -

i'm using plugin advanced custom fields on custom post type. when enter in content custom fields , publish, looks fine when trying search words in custom field doesn't show up... i need content searchable. i'm displaying custom fields using code <?php echo get_post_meta($post->id, 'course-code', true); ?> can please. post meta not included in wordpress default search. use plugin relevanssi , extends wp's search functionality.

java - hide passed parameter from jsp to struts2 action class -

<s:url action="someaction" var="act"> <s:param name="param1">value1</s:param> </s:url> <s:a href="%{act}">go action</s:a> by clicking go action link, address www.example.com/someaction?param1=value1 want hide passed parameters (param1=value1) method="post" in submitting of form. there anyway can it? thanks. to hide passed parameter need submit form. should prevent default behavior of click event , replace form event. in example <s:form id="f1" action="someaction"> <s:hidden name="param1" value="value1"/> <s:url action="someaction" var="act"/> <s:a id="a1" href="%{act}">go action</s:a> <script type="text/javascript"> $(document).ready(function() { $("#a1").click(function(event) { event.preventdefault(); $("#f1&qu

html - I cannot scroll down all the way on my site -

i have div element of content in it, including video @ bottom of page. issue is, when try scroll down see video, reaches half of it, , refuses scroll down further. <html> <head> <link rel="shortcut icon" href="images/favicon.ico" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> <title>arthur</title> <meta content="text/html" charset="windows-1251"> </head> <body background="images/background2.jpg"> <a href="main.html"><img class="imgborder" src="images/button.png" align="left" height="50"></a> <div id="wrapper" style="background-color:black; width:60%; margin-left: auto ; margin-right: auto ;"> <center><img width="60%" src="images/logo2.png"></center> <br>&l

ajax - How to submit JSF PrimeFaces form with selectBooleanCheckbox without refreshing the page? -

i'm using jsf primefaces make application assignment college. i'm struggling working. i'm using primefaces , have tabview contains 5 tabs. in 1 of tabs have datatable has several rows , columns. works fine, problem want submit form without rerendering (entire page). thing is, every column in datatable has selectbooleancheckbox, , when checkbox selected, button should disappear. if it's unselected button should appear. works fine onchange="this.form.submit()" or onclick="this.form.submit()" refreshes entire application, , causes first tab selected, rather 1 at. i'm looking solution able submit , re-render stuff without refreshing entire program. code: <body> <h:form id="customerform"> <p:datatable id="customerlist" var="c" value="#{customerbean.customerlist}"> <p:column> <f:facet name="header">select</f:facet>

java - Is there formula to calculate what day is for anyday? I got stuck by Project Euler # 19 -

i doing project euler #19. here states: you given following information, may prefer research yourself. 1 jan 1900 monday. thirty days has september, april, june , november. rest have thirty-one, saving february alone, has twenty-eight, rain or shine. , on leap years, twenty-nine. leap year occurs on year evenly divisible 4, not on century unless divisible 400. how many sundays fell on first of month during twentieth century (1 jan 1901 31 dec 2000)? i have searched in internet formula calculate day of week. found zeller formula outstanding. w = [c/4] - 2c + y + [y/4] + [13 * (m+1) / 5] + d - 1.(c century + 1, , y last 2 number of year) however, turns wrong when check 1900.01.01, it's should monday, according formula, 6(that saturday) i have checked lot of dates, right formula. there still fewer days doesn't match. java code below case: package number; public class countingsundays { public static int calculateweek(int year, int month, int date){ int

scala - Get `Symbol`s of method parameters via reflection -

i want call method on object via reflection, each parameter of method should set value specified type. more specific: have map[reflect.runtime.universe.symbol,any] symbol type e.g. list , double , string , any instance use. now, each parameter of method want query map , set parameter accordingly. i used typeof[t].members.collect ... obtain method scala.reflect.methodsymbol , don't know how obtain correct symbol . elements in method.paramss example val a not symbol of type of a . method.paramss gives list of lists (one each parameter list) contain termsymbol each argument. each termsymbol has typesignature method returns type , has typesymbol method should give symbol you're looking for. for example: scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala> class foo { def foo(s: string, i: int) = s * } defined class foo scala> val params = typeof[foo].member(newtermname("foo")).asmethod.

c# - JSON Parsing error -Invalid Character at position 0 -

i trying parse click method using windows.data.json; private async void getjson_click(object sender,routedeventargs e) { var client=new httpclient(); client.maxresponsebuffersize=1024*1024; var response= await client.getasync(new uri(the url here)); var result = await response.content.readasstringasync(); var component=jsonarray.parse(result); } the following error message - winrt information :invalid character @ position 0. invalid json string. this json data trying parse: {"x-yz-12345/ab.cd" :{"pm1":"f","pm2":"47.12"}} any highly appreciated. it not array object. try jsonobject . string result = @"{""x-yz-12345/ab.cd"" :{""pm1"":""f"",""pm2"":""47.12""}}"; var jobj = jsonobject.parse(result);

Appropriate use of Java generics on collection -

i've never had chance play generics before (as in writing classes generics), need arises, , i've come across confusion. there's interface, meant wrapper of something . implementations not collections, so, every instance has access 1 something . public interface resource<t> { // expected operations: void write(resourcestate state); resourcestate read(); } as implementations, expect have exclusiveresource<t> , , shareableresource<t> , differ mainly/only in locking scheme used (regular lock, , read-write lock, respectively). how read , write performed, i'm planning on using strategy pattern. instance, might have // implement strategy<file>. filestrategy fs = new filestrategy(); resource<file> r = new exclusiveresource<file>(fs); now, i've got sort of collection of these resources, say, resource pool. i'd map key each resource, in resource pool, , i'd add, retrieve , remove resources, i'm

java - Can't authorize with Login Button using Facebook app -

i have problem authorization using login button in android app. this code: loginbutton fbbutton=(loginbutton)view.findviewbyid(r.id.fb_button); list<string> permissions = arrays.aslist("publish_actions"); fbbutton.setpublishpermissions(permissions); fbbutton.setuserinfochangedcallback(new loginbutton.userinfochangedcallback() { @override public void onuserinfofetched(graphuser user) { if(user!=null){ //saving username sharedpreferences } } }); session session = session.getactivesession(); if(session!=null && session.isopened()) { //some actions } it works if haven't installed facebook app @ phone. app shows me webview , can login. if have installed facebook app @ phone app shows dialog , nothing. if app linked facebook account can login in app using facebook app.

javascript - Checking url exists with jquery/ajax -

this has me totally confused. i'm trying run through series of youtube ids check if videos still exist. i have ids in array , want check gdata api see if xml results or video not found 404 message. i found function on check each id , add row table. var ytarray = array of youtube ids var yttitles = array of matching titles vids var urlexists = function(url, callback){ $.ajax({ type: 'head', url: url, success: function() { callback(true); }, error: function() { callback(false); } }); } var length = ytarray.length, (var = 0; < length; i++) { urlexists('http://gdata.youtube.com/feeds/api/videos/'ytarray[i], function(success) { if (success) { $('#rows').append('<tr><td>'+yttitles[i]+'</td><td>'+ytarray[i]+'</td><td style="color: g

c# - Which is the best practice to call a method every x seconds? -

i have program controls , communicate microprocessor. program sends commands microprocessor , receives feedback @ same time command sent showing same in various text boxes.this activated/fired command control. need implement feedback not related command , therefore not activated user, (current , temperature measurement) relevant status of machine controlled micro. not idea time message sent on micro side, rather receive information , process same every x seconds on pc side. in way can include selector different update intervals. controlling motor , heater. the question is: best practice call relevant classes process such messages( current , temperature), timer, new thread timer, backgroundworker,something else? interface: recommend create startpoll() , endpoll() inside controller class: place, necessary information avoid multiple-call, interleaving etc. in scope. implementation: recommend spinning off dedicated thread: thread pool , other built-in mechanisms not de

oracle11g - Grails: Error while trying to configure with Oracle 11g XE -

i have oracle 11g xe (express edition) instance installed locally. make grails db environments. have username/password oracle user, , have ojdbc6.jar file located here: \myappname\lib\ojdbc6.jar and have not created tables in database yet - assuming grails smart enough create tables needed, if not, problem... here's datasource.groovy file contents: datasource { //oracle dbcreate = "create-drop" url = "jdbc:oracle:thin:@127.0.0.1:1521:xe" pooled = true username = "mills_gtunes" password = "*******" driverclassname = "oracle.jdbc.driver.oracledriver" // dialect= "org.hibernate.dialect.oracle10gdialect" dialect= "org.hibernate.dialect.oracledialect" properties { maxactive = -1 minevictableidletimemillis=1800000 timebetweenevictionrunsmillis=1800000 numtestsperevictionrun=3 testonborrow=true testwhileidle=tru

c# - Understanding System.Threading.Tasks behavior -

i trying performance optimization using tasks take advantage of parallel threading in .net 4.0. i have made 3 methods returns collections of objects or object. lets call them methoda, methodb , methodc. inside of methodb have long-running delay - approximately 5-7 sec. var person = new person(); person.a = task.factory.startnew(() => mystatic.methoda()).result; person.b = task.factory.startnew(() => mystatic.methodb()).result; person.c = task.factory.startnew(() => mystatic.methodc()).result; now expecting person.a , person.c properties set / populated before person.b, have difficulties testing / debugging verify assumptions. i have added parallel watch on 3 properties, debugging through not clarifying things me. also proper way me optimize multiple calls methods, if populating main object? in case have 5-7 different methods gather data from, , make them parallel of them relatively time-consuming. your assumption wrong. result property of task wai