Posts

Showing posts from March, 2015

how to define a rule of a pattern repeated by a fixed number of times using antlr grammar -

Image
i know '+', '?' , '*'. if want repeats for, say, 5 times? example, if identifier must string of hexdecimal numbers of length 5? to more specific, i'm thinking define general lexer rule of unlimited length, , then, @ parsing time count how many time repeated, if equals 5, rename type of token, how can this? or there easy way? at parsing time count how many time repeated, if equals 5, rename type of token, how can this? or there easy way? yes, can disambiguating semantic predicate ( explanation ): grammar t; parse : (short_num | long_num)+ eof ; short_num : {input.lt(1).gettext().length() == 5}? num ; long_num : {input.lt(1).gettext().length() == 8}? num ; num : '0'..'9'+ ; sp : ' ' {skip();} ; which parse input 12345 12345678 follows: but can change type of token in lexer based on property of matched text, this: grammar t; parse : (short | long)+ eof ; num : '0'..'9'+

spring - LazyInitializationException even with OpenEntityManagerInViewFilter -

i trying use openentitymanageinviewfilter, keep having lazyinitializationexception. people had similar problems when having entitymanager initialized twice - seems not case. in exception log can see, filter correctly firing. web.xml: <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation=" http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>web-application</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>web-application</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <context-param>

Count number of redirections using HTMLUnit -

i using htmlunit track 302 redirection(s). when visit page instance of webclient , 1 or more redirections might involved before landing on url. once do, mywebclient.setredirectenabled(true); , can http status code using currentpage.getwebresponse().getstatuscode(); , check if 302. problem how track sequence of redirections total number of redirections before landing on page. idea? in case still need solution, com.gargoylesoftware.htmlunit.util.webconnectionwrapper can used keep track of requests , change response (change status code stop further redirects)

How to parse json in bash or pass curl output to python script -

i'm looking find way have pretty print of curl's output in json. wrote short python script purpose, won't work pipe don't want use subprocesses , run curl them: so python: #!/usr/bin/python import simplejson pprint import pprint import sys print pprint(simplejson.loads(sys.argv[1])) and json information is: {"response": {"utilization": {"eic": [{"date": "2012.03.06", "usage": []}, {"date": "2012.03.07", "usage": [{"srvcode": "svc302", "upload": 267547188, "api-calls": {"filegetinfo": 30, "getuserstoragequota": 0, "setuserstoragequota": 0, "fileuploadflashinit": 31, "getapisessionuser": 0, "setfileaccesscontrol": 0, "filegetpreviewurl": 0, "filestartmultipartupload": 0, "getservicequota": 0, "filegetpreviewurlsforbunch": 10, "x

Cannot call custom-made Javascript function -

possible duplicate: cannot call javascript function cannot call javascript function i have same problem link above. still don't know solution problem hope can me. thanks. make sure there aren't invisible elements in front of input tag causing problems. make sure that, if there's event propagation, earlier click events preventing default behavior. the function syntax in related question accurate, , work on @ least local machine (safari).

reporting services - SSRS: Top n AND Bottom n (filter) -

is there way can filter in ssrs return top n , bottom n e.g. if have numbers -50 through +50 and filtered on top 5 , bottom 5 i expect see -50,-49,-48,-47,-46,46,47,48,49,50 is possible, allows when i've tried appears ignore second filter you can defining 2 groups. 1 group has filter top 5 , other count of records less 5 bottom n filter this technique described in full @ http://www.bidn.com/blogs/mikedavis/ssis/172/top-n-bottom-n-grouping-in-ssrs-2008 if there chance on getting duplicate records @ boundary need retrieve boundary value , return matching value or (more/less depending on top/bottom). the duplicate handling can done eg http://www.bidn.com/blogs/mikedavis/ssis/1875/ssrs-top-n-and-bottom-n-reporting-with-duplicates

php - Magento - Adding page number to title on products listing -

i have extension uses products list block show products grid filter attribute (the extension attribute info pages ). in "_preparelayout" function of extension block extension sets page's title , description using code : $head = $this->getlayout()->getblock('head'); . . . $head->settitle($title); head->setdescription($des); i want add text title , description in format : $page_info = "page of b "; $title = $page_info . title; $items_info = "listings x-y (out of z) "; $des = items_info . $des; i've tried code order current page, last page, number , items , on : $html_pager = mage::getblocksingleton('page/html_pager'); $html_pager->setcollection($product_collection); $limit = mage::getsingleton('core/app')->getrequest()->getparam('limit'); if(empty($limit)) { $limit = 8; } $html_pager->setlimit($limit); $lastpagenumber = $html_pager->getlast

c# - MSBuild vs devenv for command line builds -

i wondering: difference between using msbuild , devenv when compiling solutions command line? one obvious thing noticed msbuild build dependent projects not contained within solution, while devenv not. are there other? there special flags 1 pass msbuild make match devenv build exactly? p.s. i'm using visual studio 2010 sp1 according msdn blog entry try minimize differences, exist (i.e. using integrated c# compiler instead of csc.exe or setting buildinginsidevisualstudio property) done optimize performance of builds.

C# assigning elements of a list to a list of variables -

in perl 1 can following ($a, $b, $c) = split(',', "aaa,bbb,ccc"); does know if there equivalent in c# other doing following? var elements = "aaa,bbb,ccc".split(','); var = elements[0]; var b = elements[1]; var c = elements[2]; or there alternative doing above more concisely? no there no other way in c#. there hope in .net - namely f# :d do let [| a; b; c |] = "aaa,bbb,ccc".split(',')

HOWTO set parameter via "result" tag in struts2 and retrieve it in the resulting template jsp -

i have workflow need render exception page. exception page generic , can called form various situations. need display custom text in each of these exception pages. figured can set "param" in result tag & automatically available in eventual jsp page. unable retrieve (or set) it. here relevant code - struts.xml - <global-results> <result name="tv_access_not_alllowed"> <param name="location">/jsp/base/exception/accessnotallowedexception.jsp</param> <param name="appdisplayname">television</param> </result> <result name="radio_access_not_alllowed"> <param name="location">/jsp/base/exception/accessnotallowedexception.jsp</param> <param name="appdisplayname">radio</param> </result> </global-results> in jsp page tried below options -

unit testing - Looking for Open Source Java Projects that use JUnit and Ant -

i doing research , looking open source java projects use junit , ant . ideally have projects vary in size/complexity/domain test suite coverage. i seem having hard time finding suitable open source projects fit these criteria: project has number of junit test cases all junit test cases can ran single test class (i.e., junit testsuite) the project uses ant building , testing i sure community benefit list of usable open source projects fitting aforementioned criteria. possible learn projects use these technologies. side bonus researchers identify suitable open source projects research. the following suitable open source project according criteria: jgap joda-time jsr-166 mark4j well, bumped onto jsr-166 , java specification request various concurrency utilities. source code has ant task @ top level , pretty extensive junit-based testsuite. added benefit, units under test classes included in jdk, has couple of advantages: they documented, not case.

build automation - Is it possible to launch Gradle tasks from Ant? -

i researching replacements ant. i've looked @ gant , gradle . is possible kick off gradle task ant? possible in gant taskdef. <taskdef name = "gant" classname = "org.codehaus.gant.ant.gant" classpathref = "classpath" /> <gant /> is there similar gradle? i'm eager start migrating ant gradle, have large ant infrastructure , gradle build scripts create need callable ant. thanks! gradle doesn't offer ant task run gradle build ant. invoke gradle command (like gradle build ) ant. in terms of ant integration, gradle offers 2 features: importing ant builds, , reusing ant tasks. gradle different gant. gradle entire new build system; gant thin layer above ant.

c++ vector problems -

i working std::vector hold objects have dynamically allocated members, , when go put things vector few things happen not understanding. i call push_back() , use constructor of objects argument, reason goes destructor of object. why this; should adding not deleting? i call push_back() second time doing same before, time throws illegal memory access @ dbgdel.cpp operator delete (line 52). delete should never called in constructor, or push_back() . i uncertain sections of code pertinent question lines in question pretty entrenched in method. edit: code added class thing{ int** array; int size; // of square array point current; // location thing(int _n){ // allocates, , gives values array, , members // constructor } }; class thingmgr{ thing * control; thing * current; thing * previous; int size; // size of all. same use in thing thingmgr(int _n){ size = _n; control = new thing(size); curre

bash - How to check the validity of a remote git repository URL? -

within bash script, simplest way verify git url points valid git repo , script has access read it? protocols should supported git@ , https:// , , git:// . curl fails on git:// protocol. git@github.com:username/example.git https://username@github.com/username/example.git git://github.com/username/example.git note: i'm not asking check see if url syntactically correct, need verify repo exists @ url location entered within bash script. as seen in this issue , can use git ls-remote test address. if need debug git calls set git_trace=1 . eg: env git_proxy_commadn=myproxy.sh git_trace=1 git ls-remote https://... " git ls-remote " quickest way know test communications remote repository without cloning it. hence utility test issue. you can see used detecting address issue in " git ls-remote returns 128 on repo ".

text - Vim - Trying to go to next line with right arrow key -

possible duplicate: automatically go next line in vim does know why vim not allow go next line using right arrow key using up/down? is there way fix this? thanks in advance! zorgatone. i think can solve problem putting in vimrc file: set whichwrap+=<,>,h,l,[,] you can remove h , l if don't want them go next line.

python - Combining two Google App Engine datastore results? -

i'm trying combine 2 google app engine datastore results. because want list them in template. for example: other_user_answers = useranswer.gql("where user = :1", user.key()).fetch(500) my_answers = useranswer.gql("where user = :1", me.key()).fetch(500) i want combine these results based on question.key().id(). can in template: {% other_user_answer in other_user_answers %} question #{{other_user_answer.question.key.id}}<br> user: {{other_user_answer.answer}} me: {{other_user_answer.my_answer}} {% endfor %} i'm not sure if i'm explaining best way or not! along lines. also, i'm not quite sure google app engine datastore results come in (like list, dict, etc), i'm not quite sure i'm working with. edit more explanation: users going answer bunch of questions. when i'm logged site , go different user's page (jimmy). want list of jimmy's answers of answers next well. pull table useranswer , answers

ios - Accessing a UITableView when a UINavigationController gets in the way (in a UISplitViewController) -

i have uisplitviewcontroller set so: -(ibaction)makestory:(id)sender{ nslog(@"makestory:"); makestorytableviewcontroller = [[makestorytableviewcontroller alloc] initwithnibname:@"makestorytableviewcontroller" bundle:nil]; makesentencetableviewcontroller *detailviewcontroller = [[makesentencetableviewcontroller alloc] initwithnibname:@"makesentencetableviewcontroller" bundle:nil]; uisplitviewcontroller *splitviewcontroller = [[[uisplitviewcontroller alloc] init] autorelease]; uinavigationcontroller *rootnav = [[[uinavigationcontroller alloc] initwithrootviewcontroller:makestorytableviewcontroller]autorelease]; uinavigationcontroller *detailnav = [[[uinavigationcontroller alloc] initwithrootviewcontroller:detailviewcontroller] autorelease]; splitviewcontroller.viewcontrollers = [nsarray arraywithobjects:rootnav, detailnav, nil]; splitviewcontroller.delegate = makestorytableviewcontroller; storybotappdelegate

"Timeout expired" error, when executing view in SQL Server 2008 -

i've written query in sql server 2008. query takes 4 minutes execute. need query view . so, i've created view query , when try execute view creation script, shows following error: timeout expired. timeout period elapsed prior completion of operation or server not responding. the query is: select t.jrnno, (select sum(t1.amount) dbo.t_sh t1 (t1.b_or_s = '1') , (t1.jrnno = t.jrnno)) buy, (select sum(t2.amount) dbo.t_sh t2 (t2.b_or_s = '2') , (t2.jrnno = t.jrnno)) sale, sum(t.amount) total, sum(t.h_crg) howla, sum(t.l_crg) laga, sum(t.taxamt) tax, sum(t.commsn) commission dbo.t_sh t (t.tran_type = 's') , (t.jrnno not in (select distinct jrnno dbo.t_ledger)) group t.jrnno t_sh , t_ledger both tables have 100k rows. possible reason , how can overcome this? update: select t.jrnno, sum(case when t.b_or_s

matlab - First differences filter -

i beginning in signal processing , professor asking me first differences filter timeserie. know supposed use filter() function don't know numerator (b) , denominator (a) coefficient vectors supposed use. first differences , first-order same ? first, should read on matlab's documentation of filter function . if want take first difference, you're looking generate series: 1 * y(n) = 1 * x(n) - 1 * x(n - 1) which corresponds vector = 1, , b = [1, -1], matlab code like: y = filter([1,-1],1,x);

Run-time mocking in C? -

this has been pending long time in list now. in brief - need run mocked_dummy() in place of dummy() on run-time , without modifying factorial() . not care on entry point of software. can add number of additional functions (but cannot modify code within /*---- not modify ----*/ ). why need this? unit tests of legacy c modules. know there lot of tools available around, if run-time mocking possible can change ut approach (add reusable components) make life easier :). platform / environment? linux, arm, gcc. approach i'm trying with? i know gdb uses trap/illegal instructions adding breakpoints ( gdb internals ). make code self modifiable. replace dummy() code segment illegal instruction, , return immediate next instruction. control transfers trap handler. trap handler reusable function reads unix domain socket. address of mocked_dummy() function passed (read map file). mock function executes. there problems going ahead here. found approach tedious , requir

javascript - How to calculate an angle from points? -

i want simple solution calculate angle of line (like pointer of clock). i have 2 points: cx, cy - center of line. ex, ey - end of line. result angle (0 <= < 360). which function able provide value? you want arctangent: dy = ey - cy dx = ex - cx theta = arctan(dy/dx) theta *= 180/pi // rads degs erm, note above not compiling javascript code. you'll have through documentation arctangent function. edit: using math.atan2(y,x) handle of special cases , logic you: function angle(cx, cy, ex, ey) { var dy = ey - cy; var dx = ex - cx; var theta = math.atan2(dy, dx); // range (-pi, pi] theta *= 180 / math.pi; // rads degs, range (-180, 180] //if (theta < 0) theta = 360 + theta; // range [0, 360) return theta; }

android - how to copy text from auto complete text box to edit box -

i developing 1 notepad kind of thing in user can enter in edit text, have provided 1 auto complete text view him in writing quick word. not getting how can add word auto text box edit box without disturbing previous written text. my try : tried code public void aftertextchanged(editable s){ string c = s.tostring(); // read content ((edittext)view.findviewbyid(r.id.et_text_area)).settext(c); } public void beforetextchanged(charsequence s, int start, int count, int after){ } public void ontextchanged(charsequence s, int start, int before, int count){ } }); which coping text in edit box deleting written text. how can add word autocompletetextview edit box without deleting , when user select word, , word appear in edit box auto text box should become empty. is there api in android any appreciated. in advance try using onitemclicklistener on autocomplete. when user clicks @ word can save posi

Combine bytes php -

i need equivalent of part (in c++), on php: unsigned char arr[ 2 ]; arr[ 0 ] = 0x04; arr[ 1 ] = 0x00; unsigned short shape_types; memcpy( &shape_types, arr, 2 ) maybe knows program, can combine bytes , see result in hex , dec? the code have given not directly applicable php. php lacks typing or ability move data directly 1 memory location this. i guess want pretty following. your input array of bytes: (include 4 bytes 32 bit systems, 8 64 bit) $bytes = array( 0x04, 0x00 ); you can reduce loop: $result = 0; foreach ($bytes $byte) { $result = $result << 8 | $byte; } or array_reduce : $result = array_reduce( $bytes, function ($out, $in) { return $out << 8 | $in; } ); or combine values directly: $result = $bytes[0] << 8 | $bytes[1]; display in hex: var_dump(dechex($result)); output: string '400' (length=3)

grails encoding in html attributes -

everything working fine greek characters except greek characters included in html attributes. grails: 1.3.7 config.groovy: grails.views.default.codec = "none" // none, html, base64 grails.views.gsp.encoding = "utf-8" grails.converters.encoding = "utf-8" my test html page following: <%@ page contenttype="text/html;charset=utf-8" %> <html> <head> <title>test title</title> <meta name="keywords" content="ελληνικό τεστ"/> </head> <body> greek test encoding </body> </html> the response of server is: <html> <head> <title>test title</title> <meta name="keywords" content="&epsilon;&lambda;&lambda;&eta;&nu;&iota;&kappa;ό &tau;&epsilon;&sigma;&tau;"/> </head> <body> greek test encoding </body> </html>

jsf - javax.faces.view.facelets.FaceletException: Error Parsing /my.xhtml: Error Traced[line: 42] The prefix "f" for element "f:facet" is not bound -

i create table can display data database jsf page. found code: <h:datatable value="#{bookstore.items}" var="store"> <h:column> <f:facet name="header"> <h:outputtext value="#{msg.storenamelabel}"/> </f:facet> <h:outputtext value="#{store.name}"/> </h:column> <h:column> <f:facet name="header"> subject </f:facet> <h:outputtext value="#{store.subject}"/> </h:column> <h:column> <f:facet name="header"> <h:outputtext value="#{msg.storepricelabel}"/> </f:facet> <h:outputtext value="#{store.price}"/> </h:column> </h:datatable> when use code error message in netbeans: javax.faces.view.facelets.faceletexception: error parsing /my.xhtml: error traced[line: 42] prefix "f" element "f:facet"

How to display the soft keyboard only on the click event of edittext in android? -

my android activity has edittext . whenever screen loads soft keyboard automatically pops up. obscures visibility of screen. want display soft keyboard on click event of edittext . how can this? in code got this: inputmethodmanager imm = (inputmethodmanager)getsystemservice(context.input_method_service); imm.hidesoftinputfromwindow(password.getwindowtoken(), 0); imm.hidesoftinputfromwindow(username.getwindowtoken(), 0); where password , username textedit views. , show: imm.showsoftinputfromwindow(username.getwindowtoken(), 0);

sql server - left/right join -

i got 2 tables this: c1 1 1 2 , table 2 c1 c2 1 x 1 y 2 y and want result is: c1 c2 1 x 2 null i don't want see y need see 2 other information. with left join shows null 1 , right join 2 wont show. try this, assuming column names match table names: select c1.c1, c2.c2 c1 left join c2 on c2.c1 = c1.c1 , c2.c2 <> 'y' i'm not sure whether actual requirement. may tell more details you're trying achieve.

php - What is wrong in Facebook Credits implementation -

Image
i following official tutorial implement fb credits not working. i have added alert statements make sure code executing, alert messages, sure there no js errors , fb.ui being called. have alert messages in callback function no response received. i breaking head since 5 hours figure out wrong in code. can 1 please me. additional info on app: canvas app not published (sandbox mode enabled) not registered company. fb says can later have set country. have not registered because need come conclusion on bank account details need give because fb wont allow change (from interface) here buy.php <?php include_once '/config.php'; include_once '/fb-sdk/facebook.php'; ?> <html> <head> <title>my facebook credits page</title> </head> <body> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_us/all.js"></script> <script> fb.init({

NHibernate Cache PrevalenceProvider strange behavior -

i'm using nh prevalence cache provider happiness years, recently, team, started fall in data incorrectness can't yet explain... we setup prevalence setting cache provider , setting prevalencebase folder appdomain.currentdomain.basedirectory setting default expiration of 120 each cache registration in mappings ha region name the cache seems work, if application recycled, data returned nhibernate incorrect valid identifier, provides data seems owned entity. if delete .snapshot file in folder (appdomain.currentdomain.basedirectory) starts work fine, until next recycle wher ethe issue represented. any 1 has got same issue? 1 can issue? sure forget or ignore something, can explain better how setup prevalence appreciated in advance

php - can i retrieve visitor's facebook friends when he likes my site? -

i have been googling since morning answer meets need no luck. i included facebook button website working on, wondering after user presses button,signs in , site, there way can use retrieve list of user's friends on facebook? , post on walls instantly? not post on wall. or if wasn't possible, can retrieve friends csv file or can later send them emails example ? .. what have in mind how applications ask permission access personal data in facebook , use them in thing releted them. same point ! can done ? , if yes, how ?? if find links related or have previous experience in domain please post answer :) programming solutions, use php, yet still junior developer :). thanx in advance no, can't information want simple button. you have create app, ask permissions , user agree. here list of permissions can ask for. to build app, start here .

android - How to crop a Bitmap with a minimum usage of memory? -

in app i'm loading plenty of images web. that's working fine far: @override public void onsuccess( byte[] response ) { bitmap image = bitmapfactory.decodebytearray( response, 0, response.length, options ); ... } but in fact nice use extract of image during application process. tried this: @override public void onsuccess( byte[] response ) { bitmap source = bitmapfactory.decodebytearray( response, 0, response.length, options ); bitmap image = bitmap.createbitmap( source, 0, 0, source.getwidth(), source.getheight() - 30 ); source.recycle(); source = null; ... } but app keeps crashing after loading few dozens of images (outofmemoryexception). (i guess) have 2 opportunities rid off 30 pixels of height (it's credit information, don't worry, i'm not stealing, it's okay if hide it): crop & save image less memory usage, or manipulate imageview hide bottom of image (height may vary due scaling) but need advice these te

javascript - jQuery UI DatePicker displaying wrong date -

i've got jquery ui datepicker following parameters: changemonth: true, changeyear: true, yearrange: "-16:-1", dateformat: 'dd-mm-yy' it correctly displays years 1996 till 2011. however, when select date first time, it's strangely displayed 08-03-2012. 2012 not option selection in datepicker, date produced in text box. if select date once again, it's correctly displayed - occurs first time. any ideas? you can set default date in range this: <script type="text/javascript"> $(function() { $("#birthdate" ).datepicker({ changemonth: true, changeyear: true, yearrange: "-16:-1", dateformat: 'dd-mm-yy', defaultdate: '01-01-1996' }); }); </script>

ruby on rails - Is using assert_select correct for RSpec controller tests? -

i've been unable find documentation or advice on writing rspec controller tests. specifically, should use rails' assert_select feels unlike rspec or there alternative it? is example below best practice? describe articlescontroller render_views let(:article) { create(:article) } describe "show" "should display article title" :show, id: article response.should be_success assert_select "h1", article.title end end end i don't wish write separate view tests that's pretty inconvenient. you should able use following code check title content: page.should have_selector("h1", :text => article.title) update : noted (with -1) answer wrong, page variable set capybara after call visit method (i young when answered :p). it's use in integration tests not in functional tests (controller) you're trying do. short answer : no, it's not correct use assert_select in controll

jQuery: full Page horizontal slide -

can me full page slide left , right. want create fixed header links , want slide bottom div left or right. sample webpage for example, lets main content x pixels wide. create large div 3x pixels wide, contains 3 inline divs x pixels wide each. you can simulate sliding adjusting margin-left of outermost div. when margin-left 0, leftmost child div visible. when equals -x , middle content show, , on. make sure set overflow:hidden outer div. this should enough started. unless looking code you.

amazon s3 - Ruby AWS::S3::S3Object (aws-sdk): Is there a method for streaming data as there is with aws-s3? -

in aws-s3, there method (aws::s3::s3object.stream) lets stream file on s3 local file. have not been able locate similar method in aws-sdk. i.e. in aws-s3, do: file.open(to_file, "wb") |file| aws::s3::s3object.stream(key, region) |chunk| file.write chunk end end the aws::s3:s3object.read method take block parameter, doesn't seem it. the aws-sdk gem supports chunked reads of objects in s3. following example gives demonstation: s3 = aws::s3.new file.open(to_file, "wb") |file| s3.buckets['bucket-name'].objects['key'].read |chunk| file.write chunk end end

ios - viewDidDisappear not called when use presentViewController -

i have uiviewcontroller having method: - (void)viewwilldisappear:(bool)animated { [super viewwilldisappear:animated]; nslog(@"disappear"); lastknownorientation = [self interfaceorientation]; } -(void)opensendvc{ sendmsgviewcontroller *vc = [[sendmsgviewcontroller alloc]initwithnibname:@"sendmsgviewcontroller" bundle:nil]; [self.navigationcontroller pushviewcontroller:vc animated:no]; } in second view controller ( sendmsgviewcontroller ) viewdidload have following: [self presentviewcontroller:picker animated:yes completion:null]; where picker uiimageviewpicker . the problem is, when call method opensendvc new controller opened, viewwilldisappear (of first viewcontroller) not called. that correct behavior. here's excerpt viewwilldisappear: uiviewcontroller api docs : this method called in response view being removed view hierarchy. method called before view removed , before animations configured. presenti

App to allow a Facebook user post to Business Page Timeline? -

i don't know if possible (i don't know graph api yet). i've seen lot of posts page posting user's profile, not other way around. want write app allows user post business page's timeline. users can normally, can't add things @ date (which vital project). so in short app needs to: let users post business page timeline let users specify date in timeline (ex: did on date) i know admins can edit time , date, can open option users?

objective c - Send NSString via Game Center -

i want send nsstring form 1 1 iphone/ipad via gamecenter crash exc_bad_access here in .h file typedef enum { kmessagetyperandomnumber = 0, kmessagetypegamebegin, kmessagetypesubmit, kmessagetypeexchange, kmessagetypepickup, kmessagetypepass, kmessagetypegameover } messagetype; typedef struct { messagetype messagetype; } message; typedef struct { message message; nsstring *submittile; } messagesubmit; and here in .m file - (void)senddata:(nsdata *)data { nserror *error; bool success = [[gchelper sharedinstance].match senddatatoallplayers:data withdatamode:gkmatchsenddatareliable error:&error]; if (!success) { cclog(@"error sending init packet"); [self matchended]; } } -(void)sendsubmit:(nsstring *) submittile { messagesubmit message; message.message.messagetype = kmessagetypesubmit; message.submittile = submittile; nsdata *data = [nsdata datawithbytes:&message length:sizeof(me

Retrieve the saved location of the android-sdk from eclipse -

is there way saved location of "android-sdk" within eclipse? if go window -> preferences -> android . there text field containing location of android-sdk. there way query eclipse value in ant script or other means? on mac, found value in file stored in workspace: {workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings/com.android.ide.eclipse.adt.prefs file contents: com.android.ide.eclipse.adt.fixlegacyeditors=1 com.android.ide.eclipse.adt.sdk=/users/jakuben/documents/android_dev_environment/android-sdk-macosx eclipse.preferences.version=1

lighting - working with openGL -

Image
im trying little 3d scene opengl , include bit of lighting, im fine scene (although isnt special) , im trying add lighting give effect. can add material podium (which isnt textured) , gives me light , textured not apply material defies point of having lights. heres of code. // setup gl_light0 gllightfv(gl_light0, gl_ambient, lightambient); // setup ambient light gllightfv(gl_light0, gl_diffuse, lightdiffuse); // setup diffuse light gllightfv(gl_light0, gl_specular, lightspecular); // setup specular light gllightf(gl_light0, gl_constant_attenuation, ca); gllightf(gl_light0, gl_linear_attenuation, la); gllightf(gl_light0, gl_quadratic_attenuation, qa); gllightf(gl_light0, gl_spot_cutoff, 180.0f); gllightf(gl_light0, gl_spot_exponent, 0.0); // setup gl_light1 gllightfv(gl_light1, gl_ambient, lightambient); // setup ambient light gllightfv(gl_light1, gl_diffuse, lightdiffuse); // setup diffuse light gllightfv(gl_light1, gl_specular, lightspecular); // setup spe

networking - Network Requirements For WASD Game Server -

i wonder whether possible build single game server capable of handling lot of players in game uses wasd controls (as know, wasd generates way more data on network point-and-click). not talking server-side code performance (because know that) wonder whether network allow this. , not talking many game servers serving different rooms or stuff because it's different story. as game, not benefit cdn , forced rely on single server. guess capable if players located around server (for example in usa or eu only) playable on other side of globe, example australia? plus, wonder, how long take signal travel eu or around globe? latency? have heard people reporting latency being more second or so, unplayable wasd. your game server doesn't need receive every keypress event. that's client's for. client handles , responds input events example updating player's location. new location data what's sent server, delta last location. in short, here's basic se

How to read html with jQuery in data in jQuery get method $.get -

in jquery statement: $.get(someurl, function (data) { ### }); i receiving like: <div class="somediv">john smith</div> question is: how jquery read data html $("div.somediv").text() in function response ### placed? i need read div text through div class name, because can have multiple divs different class names if data == '<div class="somediv">john smith</div>' then should work $(data).text() if data has bunch of other html can filter after making jquery object var text = $(data).filter('div.somediv').text(); if need selection later on, can add body this var $data = $(data) $data.length && $(body).append($data.css('display','none')); and later select $('div.somediv').text()

android - Bluetooth communication on Samsung Galaxy S -

i have android application running on samsung galaxy s phone. application collects sensor data via bluetooth device. part, there no data being sent/received. have set application "auto-reconnects" bluetooth device in case connection "lost". i observe after 1.5 hours of application running, phone loses connection bluetooth device , auto-reconnect fails. the sending of sensor data device phone "mission critical". how can ensure connection not lost. solution needs optimal. is, conserve battery, phone needs able sleep / hibernate. you should listen incoming connections when disconnected (use bluetoothserversocket). should run in foreground service, never stopped. service monitor bluetooth connection state (disconnected, listening, connected) , spam threads each situations (asynctasks). the listening thread should said in android documentation : to create listening bluetoothserversocket that's ready incoming connections, use blueto

version - versionCode vs versionName in Android Manifest -

i had app in android market version code = 2 , version name = 1.1 however, while updating today, changed version code = 3 in manifest mistake changed version name 1.0.1 , uploaded apk market. now, users of app update notification on phones or not? or should redo process again? reference link android:versioncode an internal version number. number used determine whether 1 version more recent another, higher numbers indicating more recent versions. not version number shown users; number set versionname attribute. value must set integer, such "100". can define want, long each successive version has higher number. [...] android:versionname the version name shown users. attribute can set raw string or reference string resource. string has no other purpose displayed users. versioncode attribute holds significant version number used internally. reading it's pretty clear versionname that's shown user, versioncode matters. keep increasing ,

Where is the correct place to insert odd snippets of configuration code in Ruby such as the config for awesome_print? -

sometimes need insert chunk of code rails app perform kind of config. seem missing regards should go. let's say, example, awesome_print. eliminate it's color printing use in logs , need in production , staging only. i've tried inserting environment.rb , application.rb , initializer , such, yet none of these appropriate. each result in various errors. where insert config line such as: if rails_env == 'production' ap object, options = {:plain =>true} if your code example doesn't work because object undefined. if want set defaults gem can create file called awesome_print.rb in initializers directory. if rails.env.production? || rails.env.staging? awesomeprint.defaults = { :plain => true } end see 'setting custom defaults' section on github page: https://github.com/michaeldv/awesome_print the linked section uses .aprc file in user's home directory should work same initializer.

java - Why I can't visual the String with Graphics drawString method -

it can see pdf.png in new picture, can't see string "hello" in new picture public void generateimage() throws exception{ int width = 220; int height = 50; bufferedimage image = new bufferedimage(width,height,bufferedimage.type_int_rgb); graphics g = image.getgraphics(); g.setcolor(new color(255,255,255)); g.fillrect(0, 0, width, height); font font = new font("宋体",font.bold,10); g.setfont(font); bufferedimage image2 = imageio.read(new file("data/icon/pdf.png")); g.drawimage(image2, 0, 0, 44, 42, null); g.drawstring("hello", 50, 5); g.dispose(); file f = new file("data/icon/"+filename+".png"); fileoutputstream fos = new fileoutputstream(f); imageio.write(image,"png",fos); fos.close(); } g.drawstring("hello", 50, 5); on line manipulate coordinate values, i.e. 50 ,

ios - Programatically switching tabs using selectedViewController property -

i've used search already, haven't found answer. trying switch this: [self. tabbarcontroller.selectedviewcontroller optionsviewcontorller]; and this: [self.tabbarcontroller.selectedviewcontroller = self.tabbarcontroller.viewcontrollers objectatindex:3]; but doesn't work, tried , advice change self.tabbarcontroller.selectedindex but changes @ tab bar not view. this should work. self.tabbarcontroller.selectedviewcontroller = [self.tabbarcontroller.viewcontrollers objectatindex:3];

How can I use Ruby's to_json in a subclass and include super's json? -

#!/usr/bin/env ruby require 'json' class def to_json(*a) { :a => 'a' }.to_json(*a) end end class b < def to_json(*a) super({ :b => 'b' }) end end puts b.new.to_json produces {"a":"a"} how produce {"a":"a", "b":"b"} in reasonable way? i'm using ruby 1.9.3 , latest json gem. a related question is: arguments *a to_json? i've scoured docs no avail. you have 2 hashes {:a=>'a'} , {:b=>'b'} in 2 classes, they're encapsulated i.e. hidden outside world. way can see parse json string hash , merge them, convert result json. class b < def to_json(*a) json.parse(super).merge({:b=>'b'}).to_json end end but here small difference: you're merging {:a=>'a',:b=>'b'} , got {"a":"a","b":"b"} *a parameter set options json format

unit testing - Mix services and leaf objects in constructor for dependency injection? -

i attempting make code testable possible, means using dependency injection correctly. i have read it's okay use new() instantiate object, if object meets criteria . notably - should not accept "non newable" in constructor. for example, should able go new form('signup'); because there no way di container know how create "signup" form ahead of time. i can make work of time, i'd form able validate itself, using third party validator, like: $form->validate()->isvalid(); ...which means have pass in validator service. i'd prefer have validator included because of time form need validated, , i'd have go through work set validator on own otherwise. is okay, in instance do: new form(validator $validator,$name); i'd value or object object requires in order in valid state 1 of object's dependencies; in example entirely validly include form's name. don't think type of dependency can used whether sho

c# - Force WaitCursor to the parent form of a modal form -

i have form displays loading animation while backgroundworker doing work, , closes when work complete. show following code: using (backgroundworker bw = new backgroundworker()) using (loadingpopup loadingpopup = new loadingpopup(bw)) { bw.dowork += delegate { domywork(); }; loadingpopup.showdialog(this); } my loadingpopup form starts background worker in onshown, , when background worker finishes closes itself. i want have waitcursor displayed if user hovers on part of parent form or child form. i've tried adding code loadingpopup onshown event set parent.cursor, owner.cursor, this.cursor, , cursor.current waitcursor, setting them cursor.default in onclosed event. when hover on parent form default cursor. any way force cursor or set application-wide cursor? edit: have tried inserting change cursor before , after showdialog line of code in parent. still did not work. prefer loadingpopup manage cursor anyway reusability. i tried setting

c# - Bind a List<Group> to ComboBox? -

i have following xaml: <combobox name="groupcombobox" itemssource="{binding path=myservicemap.groups}" displaymemberpath="{binding name}"/> in code behind set this.datacontext viewmodel. private servicemap _servicemap; public servicemap myservicemap { { return _servicemap; } set { _servicemap = value; onpropertychanged("myservicemap"); } } my servicemap class is public class servicemap { //other code public list<group> groups = new list<group>(); } and finally: public class group { public string name { get; set; } } unfortunately, not working. how can bind combobox show group name? there 2 problems code. first bindings work on properties, binding couldn't find group field. change property. public class servicemap { public list<group> groups { get; set; } } the second 1 di

java - Can I use Perf4J across processes? -

i'm integrating perf4j in distributed application, task can prepared on 1 server , executed on another. we'd able track performance of these tasks including inter-process transport component, standard perf4j implementation doesn't seem work that. it can serialize stopwatch object, seems more efficient pass start time value in work packet , initialize stopwatch start time on receiving end (the servers' clocks synchronized using ntp). see stopwatch constructor takes start time , elapsed time, javadoc says "should not called third party code." is there way track performance of task begins in 1 process , completes on another, using perf4j or tool?

How can I connect to redis using php but without use a client library -

i'd know way connect redis using php scratch (without use client predis)? thanks. you can connect using fsockopen , communicate sending raw commands , reading server response: $c = fsockopen('127.0.0.1', 6379, $errcode, $errstr); $rawcommand = "*2\r\n\$4\r\necho\r\n\$12\r\nhello world!\r\n"; fwrite($c, $rawcommand); $rawresponse = fgets($c); echo $rawresponse; // $12 $rawresponse = fgets($c); echo $rawresponse; // hello world! to use way, should familiar redis protocol: http://redis.io/topics/protocol

ios - UITableView delete/add row causes CoreData: Serious Application Error if another object has been selected in the MasterView of a SplitViewController -

update 18/3 #2. i've started counting beginupdates , endupdates make sure they're even. right before there's exception, out of sync. not sure why though. update 18/3: think i've found problem , i'm not sure if know how fix it. after experimenting couple hours, found crash app when had selected more 1 item in master tableview of svc during session. when item selected in master tableview, detail table view gets new object set , refreshtables called if it's halfway through update/move/delete/insert cycle. hence problem; think has instructions update old story object though new story object has been set on detailviewcontroller. how can animation/coredata/tableview updates processed before new story set in detail view? save changes managedobjectcontext when seteditting == no. i'm guessing need make custom setstory setter processes updates uitableview/coredata set before accepting new object? this code gets called on master tableview controller of svc i