Posts

Showing posts from May, 2015

How to use more than one JSF form -

i have java ee 7 project , in web application part trying open jsf forms. however when run it, sees initial form. how can enable reach other forms? small example code: <body> <h:form id="firstform" prependid="false"> ... </h:form> <h:form id="secondform" prependid="false"> ... </h:form> </body> this answer helped me lot. , there referance problem. after correcting them, can see form structure. i know code above not nested form structure, other people curious issue, cannot make nested forms in html5 (for both <h:form> , <form> ). careful template. good luck!

php - want to write code for popup window from my given code -

i have simple website written php code. have detect button on page , given below code writen function problem need popup window when detect link clicked. have tired set code in created code not able .kindly please me solve problem. <?php /*echo "permessi".$permessi; echo "<br>id".$id_nome;*/ if($action=='canc'){?> <h1>are sure want delect course?</h1> <form action="<?=$_server['php_self']?>" method="post" name="canc1" style="float: left; margin-left:25px;"> <input type="hidden" name="idcorsocanc" value="<?=$canc_id?>"> <input type="hidden" name="action" value=""> <input type="submit" name="ok" value="si,cancella" class="puls_invia"> </form> <form action="<?=$_server['php_self']?>" method="post" name...

java - GSON exclusionStrategy shouldSkipField need to know field's concrete class -

i having trouble gson exclusionstrategy implemenation.i need implement gson serialization filtering based on template. in gson. in gson exclusionstrategy , shouldskipfield , need know field's concrete class, in class hierarchy my class structure following:- class a{ string id; } class b{ string bb; string bbb; } class c extends a{ string cval; b bobj; } i want access 'id' field via class c, id field's declaring class comes instead of c. thanks in advance, preeti

delphi - How to show DBGrid.Hint when hovering with the mouse on a cell? -

while following code correctly set form1.caption text of cell mouse over, not display dbgrid.hint unless click on cell. what wrong picture? type thackgrid = class(tdbgrid); // expose protected datalink property procedure tform1.dbgrid1mousemove(sender: tobject; shift: tshiftstate; x, y: integer); var cell: tgridcoord; actrec: integer; begin cell := dbgrid1.mousecoord(x, y); if dgindicator in dbgrid1.options dec(cell.x); if dgtitles in dbgrid1.options dec(cell.y); if thackgrid(dbgrid1).datalink.active , (cell.x >= 0) , (cell.y >= 0) begin actrec := thackgrid(dbgrid1).datalink.activerecord; try thackgrid(dbgrid1).datalink.activerecord := cell.y; caption := dbgrid1.columns[cell.x].field.asstring; // form1.caption shows fine! dbgrid.hint := dbgrid1.columns[cell.x].field.asstring; // <== hint shows when click cell! thackgrid(dbgrid1).datalink.activerecord := actrec; end; end; end; call app...

python - Django model export on MySql server -

i imported external database project , thereby converting models.py file using python manage.py inspectdb > models.py command. now have edited models.py file adding class. how can export models.py file onto mysql server without hampering data in database? follow screen cast http://pressedweb.com/tutorials/django-djourney-introduction-to-south/ then search in google or stackoverflow requirements. there have threads regrading matter in stackoverflow. before doing south migration don't forget backup database.

java - Google App Engine query filter by date -

how gae filter query results date? i'm trying pass datestamp through query can't work. in google dashboard datastore viewer date field stored gd:when type format: yyyy-mm-dd hh:mm:ss when displayed on webpage displays mon jul 15 20:15:35 utc 2013. i request string mon jul 15 20:15:35 utc 2013 jsp page , parse filter isn't working. string strdatestamp = req.getparameter("stamp"); string formatstring = "eee mmm dd hh:mm:ss z yyyy"; date datestamp = null; try { datestamp = new simpledateformat(formatstring).parse(strdatestamp); } catch (parseexception e) { e.printstacktrace(); } filter filter = new filterpredicate ("date", query.filteroperator.equal, datestamp); query query = new query("example", key).setfilter(filter); date in computer systems represented time, in particular case it's internally represented unix time in milliseconds. see...

python - Getting World Coordinates with mouse in pygame -

i having trouble updating mouse position , checking entity collisions (between mouse , entity) due level scrolling. have used camera function question: how add scrolling platformer in pygame i have tried use camera function on mouse this: def update(self, target, target_type, mouse): if target_type != "mouse": self.state = self.camera_func(self.state, target.rect) else: new_pos = self.camera_func(mouse.rect, target.rect) mouse.update((new_pos[0], new_pos[1])) print mouse.rect but mouse.rect consistently set 608, 0 . can me this? mouse class looks this: class mouse(entity): def __init__(self, pos): entity.__init__(self) self.x = pos[0] self.y = pos[1] self.rect = rect(pos[0], pos[1], 32, 32) def update(self, pos, check=false): self.x = pos[0] self.y = pos[1] self.rect.top = pos[1] self.rect.left = pos[0] if check: ...

dynamic - scaling a text nav to the width of a navigation row regardless of screen size -

the page in question is: http://amytdatta.com , i'm using virb build site. i top text nav scaled width of nav bar , not have text running on next line (at least on 21" imac screen @ 1680x1050). any advice on how achieve appreciated. thanks! te way think work fin out how many nav items have, divide 100 number , make each div wide in percent. e.g. if had 5, you'd set each 1 width:20%; sit next each other. whether that's idea or not decide. may way you've designed nav doesn't work because have many items , need better way of showing them. that's design question though, not how one. hope helps.

TypeError: decoding Unicode is not supported python -

i using lxml.html parse html file , text page. bur have string has character ' example florian's due which, while printing output traceback parent_link_id_text = parent_link_id.xpath('./td[@width="400"]/text()') print (sgs_mid[0]+";"+"external"+";"+str(link_id_num[0])+";"+parent_link_id_text[0]+";"+parent_link_link[0], file = log_file_1) unicodeencodeerror: 'ascii' codec can't encode characters in position 56-58: ordinal not in range(128) then tried print (sgs_mid[0]+";"+"publicfreeurl"+";"+str(link_id_num[0])+";"+unicode(parent_link_id_text[0],"utf-8")+";"+parent_link_link[0], file = log_file_1) and traceback: typeerror: decoding unicode not supported how can solve printing string unicode cahracter? not sure if solution problem, perhaps guide in right direction. without seeing code have data, i'm going...

php - .htaccess alternative to B flag? (escape backreferences) -

i have .htaccess set following: rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewriterule ^([a-za-z0-9_-]+)/?$ profile.php?aid=$1 [l,qsa] this gets users profile fine, if username example "apple & pears" 404 page not found. believe down encoding issue ampersand. i've researched , found b flag solve problem, host's apache version below 2.2.7 when introduced. is there method replicate this? have 2 separate rules this: rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewriterule ^([^&]+)&([^/]+)/?$ /index.php?aid=$1\%26$2 [l,qsa] rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewriterule ^([^/]+)/?$ /index.php?aid=$1 [l,qsa]

intellij messes up with tabs in non-program files -

so spent time fussing on why string.split call in scala failed - trying split on tab. problem wasn't doing, rather fact intellij changes tabs spaces. fair enough, can tell intellij not files - random text files might using test/learning purposes? first, turn on settings > editor > appearance > show whitespaces , way you're sure white space characters there. next, under settings > code style > general there should use tab character check box. says "use tabs that's not java, scala, html, etc.". make sure java , scala *, etc. use tab character setting set want. unfortunately, don't know of way more fine grained file types , not use tabs vs. spaces. *i'm assuming intellij scala plugin adds tab in settings > code style .

javascript - html form not holding it's elements' attributes when being passed from web page to child iframe? -

i have form gets completed on webpage user, when user submits form, bring bootstrap modal dialog, dialog has iframe in loads form parent window calling function in so: //parent window var formtosubmit; function getform(){ return formtosubmit; } $("#submitbutton").click(function(){ //alterations elements in $("mainform") formtosubmit = $("mainform"); $("#modaldialog").modal(); //... }); //modal iframe var parentform = parent.window.getform(); $("#maindiv").append(parentform[0].outerhtml); $("form").submit(function(){ parent.window.closemodalwindow(); //not sure whether close after form submitted yet }); $("form").submit(); my problem i'm submitting these forms microsoft sql server reporting services , takes every input element parameter. have no control on this. so when user clicks submit in main form, disable elements must not set parameters, thing is; form parent window , append...

.htaccess - Redirect wordpress urls to joomla urls on the same domain -

this first question on stack overflow. site bible me , hope question not redundant. well. i'm creating news site joomla 3. site replcae , old site made wordpress. i'd set redirect rules on same domain. on wordpress news this: /ita/news or /eng/news/ on joomla conf: /ita/category/id-news.html /eng/category/id-news.html news have same title , same url both on joomla , wp there ia way on htaccess match title of news of wp links , compare last part of links of joomla site , set rewrite condition? if not possible possibilities creare redirect 301 news? this? redirect 301 /ita/news /ita/category/id-news.html thanks gabriele use redirectmatch specify pattern. redirectmatch 301 /([^/]+)/([^/]+) /$1/category/id-$2.html using mod_rewrite instead, able restrict redirection happen when url path (i.e. directory structure /eng/news/ ) physically not exist. rewriteengine on rewritebase / rewritecond %{request_filename} !-d # not dir rewritecond %{request_file...

Linq unable to hydrate an IEnumerable in a left outer join group by query -

i have left outer join group linq query: var query = idef in taskdb.taskdefinitions join iparam in taskdb.taskparameters on idef.id equals iparam.taskid nullableparameters iparam in nullableparameters.defaultifempty() join iexecution in executions on idef.id equals iexecution.taskid nullableexecutions iexecution in nullableexecutions.defaultifempty() group iparam new { definition = idef, execution = iexecution } g select new querydomain { definition = g.key.definition, parameters = g, execution = g.key.execution, }; public class querydomain { public taskdefinition definition { get; set; } public ienumerable<taskparameter> parameters { get; set; } public taskexecution execution { get; set; } } the query keeps throwing system.data.sqlclient.sqlexception (0x80131904): invalid object name 'dbo.taskparameter'. i stopped right before execution examine underlying sql statement, reason, doesn't seem...

python - Generating sublists using multiplication ( * ) unexpected behavior -

this question has answer here: list of lists changes reflected across sublists unexpectedly 13 answers nested list indices [duplicate] 2 answers i'm sure has been answered somewhere wasn't sure how describe it. let's want create list containing 3 empty lists, so: lst = [[], [], []] i thought being clever doing this: lst = [[]] * 3 but discovered, after debugging weird behavior, caused append update 1 sublist, lst[0].append(3) , update entire list, making [[3], [3], [3]] rather [[3], [], []] . however, if initialize list with lst = [[] in range(3)] then doing lst[1].append(5) gives expected [[], [5], []] my question why happen ? interesting note if do lst = [[]]*3 lst[0] = [5] lst[0].append(3) then 'linkage' of cell 0 broken , [[5,3],[]...

c++ - How to detect changes to the Windows system tray? -

Image
i've got windows 7 vm runs mandatory corporate communication systems (lync , outlook). i'd run process on windows machine monitors system tray , sends notifications host machine (xubuntu 13.04) i'm informed when email or im (i've tried seamless rdp it's ineffective solution). anything linux or network oriented can handle relative ease, not know how how query state of windows system tray (or attach event listener state changes). i'm comfortable c++ , python i'll give viable solution go. detailed state information preferable @ minimum need able detect changes in number of icons in tray. on windows, if install visual studio, among visual studio tools there useful tool, named "spy++", it's tool shows windows , gives ability see messages particular window receives. using tool, can see whole panel, contains "start button", shortcuts, tray, clock, etc. "shell_traywnd". can use "find" menu search parti...

how to disable spell checker for Android AutoCompleteTextView? -

Image
i've searched problem not found answers case. have autocompletetextview , strings suggestions (city names). android marks them red line. i think it's android's spell checker. how can prevent spell checking? found best solution: android:inputtype="textphonetic"

java - Any way to automate Eclipse workspace setup? -

i started setting new eclipse workspace new project working on. requires checking out variety of cvs repositories, including setting lot of external jars, dependencies, , build paths. apparently relatively common [and long] tasks new employees or managing code changes , wondering if kind of eclipse scripting interface can design script automates tasks cvs checkout , set dependencies? you can find overview of scripting tools/plugins in eclipse wiki . to save rampuptime new employees also: file -> import -> install software items file base-setup of plugins. share perferences file -> import -> remote preferences

matlab - Why does the randn function return a number larger than 1? -

in matlab, thought randn returns random number belongs normal distribution mean 0 , standard deviation 0. therefore, expect number in range (0,1). number not in range (0,1). please let me know wrong? you thinking of uniform distribution. normal distribution can, in theory, have big numbers, very low probability. randn has mean of 0 , standard deviation of 1. normal distribution bell-curve / gaussian shape, highest probability @ mean , probability falling off relative standard deviation. what looking rand - uniform random distribution gives numbers bounded between 0 , 1 probability @ points.

bash shell script not working as intended using cmp with output redirection -

i trying write bash script remove duplicate files folder, keeping 1 copy. script following: #!/bin/sh f1 in `find ./ -name "*.txt"` if test -f $f1 f2 in `find ./ -name "*.txt"` if [ -f $f2 ] && [ "$f1" != "$f2" ] # if cmp $f1 $f2 &> /dev/null # not work if cmp $f1 $f2 rm $f2 echo "$f2 purged" fi fi done fi done i want redirect output , stderr /dev/null avoid printing them screen.. using commented statement script not work intended , removes files first.. i'll give more informations if needed. thanks &> bash syntax, you'll need change shebang line (first line) #!/bin/bash (or appropriate path bash. or if you're using bourne shell ( /bin/sh ), have use old-style redirection, i.e. cmp ... >/dev/null ...

websphere - Why we need to specify jar dependency in MANIFEST file -

when deploying ejb jar part of ear, understand runtime jar dependencies of ejb (i.e log4j) need specified in ejb jar's manifest.mf. why this? if put log4j in same directory ejb jar, should automatically included in runtime classpath, no? why need specify log4j in manifest.mf again? on same vein, jars automatically available ejb jar @ runtime without having specify them in manifest? jars shipped websphere? you don't have specify dependencies in manifest starting java ee 5. location of libraries can specified through <library-directory> element in application.xml. defaults lib . java ee 5 supported 7.0 , higher.

How can I have threadsafe instance variables within Inlinescript block when using Powershell workflows? -

i'm using powershell 3 , playing workflows , have run across curious. using inlinescript block hold code represent task want run many instances of. have found variables declared within inlinescript block can accessed across parallel instances. my sample here has parallel process sleep random number of milliseconds can see console output multiple concurrent processes may sleep same number of milliseconds. sure, possible, it's it's clear data not threadsafe. workflow invoke-foreachparallel { param([string[]]$computers) foreach -parallel($pc in $computers) { inlinescript { "executing on $using:pc" [int]$i = get-random -min 200 -max 3000 "`t$using:pc - sleeping $i milliseconds." start-sleep -milliseconds $i "`tfinished processing on $using:pc" } } } cls invoke-foreachparallel (1..50) so, question is: how can ensure each concurrent process wo...

serial port - FTDI TTL with Linux -

in order send commands external device, use wire called ttl-232r-3v3 of ftdi. want set there specific pathways high or low. parity or stop bits not needed. my operating system ubuntu linux 13.04. i want develop java or c application, can send these commands. there error when try install driver wire: i'm following this instruction, , decided install d2xx driver. think i've installed shared object , static library described in step 2.1, anyway didn't got error messages. but when try compile sample code, described in step 3, got following output executing make -b command. for n in bitmode eeprom/erase eeprom/read eeprom/write eeprom/user/read eeprom/user/size eeprom/user/write events largeread multithread setvidpid simple timeouts ; make -c $n || exit 1; done make[1]: betrete verzeichnis '/home/robin/dokumente/java/stepper/lib/release/examples/bitmode' gcc main.c -o bitmode -wall -wextra -l. -lftd2xx -wl,-rpath /usr/local/lib make[1]: verlasse verzeic...

c++ - Linking issues with pantheios - undefined reference pantheios_init -

i have read pretty of posts relating this. link core library twice, suggested in many places. can't figure out issue is. here error: main.o: in function `pantheios_initialiser::pantheios_initialiser()': /home/awishformore/code/pantheios/include/pantheios/./internal/initialiser.hpp:119: undefined reference `pantheios_init' /home/awishformore/code/pantheios/include/pantheios/./internal/initialiser.hpp:121: undefined reference `pantheios_exitprocess' main.o: in function `pantheios_initialiser::~pantheios_initialiser()': /home/awishformore/code/pantheios/include/pantheios/./internal/initialiser.hpp:133: undefined reference `pantheios_uninit' this line makefile generates linking: g++ -wall -g -i/home/awishformore/code/stlsoft/include -i/home/awishformore/code/pantheios/include -i/home/awishformore/code/boost_1_54_0 -i/home/awishformore/code/mysql/include -l/home/awishformore/code/pantheios/lib -l/home/awishformore/code/mysql/lib -l/home/awishformore/code/bo...

c++ - I do not want the derived class to inherit the constructor function of the Base class -

as located @ title. here example: #include <iostream> using namespace std; class base { private: int nsize; public: base(){ cout << "i'm base constructor" << endl; } }; class derived : public base { int nmaxsize; public: derived(){ cout << "i'm derived constructor" << endl; } }; int main(){ derived obj; return 0; } the result: i'm base constructor i'm derived constructor you have no choice. best can pass flag base constructor disabling don't want. indicates bad design.

Using cin for input complex number in C++11 -

#include <iostream> #include <complex> using namespace std; int main(){ complex<double> p; cin >> p.real() >> p.imag(); } in g++4.7.2 works successfully, in c++11 failed compile. why? it gives me following error message: prog.cpp: in function ‘int main()’: prog.cpp:7:19: error: no match ‘operator>>’ in ‘std::cin >> p.std::complex<double>::real()’ full version: http://ideone.com/m3bhvr you can simpler this: cin >> p; format must be: (real,imag) (see: here ) or can following: double real, imag; cin >> real >> imag; complex<double> p(real, imag);

ios - Why is an init method of a child not called by a parent allocating that child in cocos2d v2.0? -

i have class: //interface @interface savingdataplist : simpletimedgamerecipe { nsmutablearray *moles; int tagcount; int molecount; ccsprite *mallet; cgpoint malletposition; } -(cclayer*) runrecipe; -(void) step; -(void) initbackground; -(void) createmoleatposition:(cgpoint)point withz:(float)z; -(void) processmolehit; -(void) addhiscorestomenu; -(void) loadhiscores; -(void) addhiscore; -(void) deletehiscores; -(void) startnewgame; -(void) gameover; -(void) step:(cctime)delta; -(void) cctouchesbegan:(nsset *)touches withevent:(uievent *)event; @end which in reunrecipe method calls this: [self createmoleatposition:ccp(50,205) withz:0]; and call corresponds method: -(void) createmoleatposition:(cgpoint)point withz:(float)z { ccspriteframecache *cache = [ccspriteframecache sharedspriteframecache]; ccsprite *back = [ccsprite spritewithspriteframe:[cache spriteframebyname:@"mole_back.png"]]; back.position = ccp(point.x, point.y);...

soql - Salesforce Column naming conventions and queries -

i trying retrieve salesforce column named "e2 instance", cannot insert space query. noticed query "account type" i'd use such syntax: select name, id, type account how query columns spaces in name? tried inserting quotes - did not work. or how list of available columns in "code" format? you must confusing field label , field api name. should e2_instance__c sure got setup -> customize -> accounts -> fields , see under account custom fields & relationships in api name column.

c# - HttpWebRequest is caching even with AllowWriteStreamBuffering false -

i'm trying implement upload progress bar on ios application. current implementation simple trick: using (stream requeststream = request.getrequeststream ()) { byte[] datatoupload = this.datatoupload; int datatouploadlength = datatoupload.length; int uploadedsofar = 0; while (uploadedsofar < datatouploadlength) { int toupload = 8192; if (uploadedsofar + toupload > datatouploadlength) { toupload = datatouploadlength - uploadedsofar; } requeststream.write (datatoupload, uploadedsofar, toupload); uploadedsofar += toupload; this.setuploadedratio ((float)uploadedsofar / (float)datatouploadlength); } the problem requeststream.write() instant until around 100kb of data sent, becomes more logical , setuploadedratio() method shown above called should. when file huge, not big deal, though can still see takes percent instantly , start percent slower. on slow connections, sending 60kb file result in sho...

java - How SLF4J-API classloading gives preference to bindings over dummy? -

if @ source code slf4j-api (any modern version, say, 1.7.5), there loggerfactory class following method: private static set findpossiblestaticloggerbinderpathset() { // use set instead of list in order deal bug #138 // linkedhashset appropriate here because preserves insertion order during iteration set staticloggerbinderpathset = new linkedhashset(); try { classloader loggerfactoryclassloader = loggerfactory.class .getclassloader(); enumeration paths; if (loggerfactoryclassloader == null) { paths = classloader.getsystemresources(static_logger_binder_path); } else { paths = loggerfactoryclassloader .getresources(static_logger_binder_path); } while (paths.hasmoreelements()) { url path = (url) paths.nextelement(); staticloggerbinderpathset.add(path); } } catch (ioexception ioe) { util.report("error getting res...

jquery - Coding a Javascript HTML5 Scroll "Camera" -

i rookie html5/javascript/php/mysql programmer started out , needs help. i trying site http://space.angrybirds.com/launch/ when scroll down, instead of scrolling down content on typical site, "camera" kind of moves in direction, @ other content. to give better idea of trying accomplish, here diagram: http://i.stack.imgur.com/lpy16.jpg (i cannot post images first post) what trying accomplish not complicated reference angry birds site, rather scrolling down instead of scrolling down, moves in zig zag manner right. do know javascript libraries angry birds site devs might have used make site? code snippets, library names, jquery examples, helpful me! pardon me if said terms wrongly, , please correct me. i think maybe looking parallax scrolling plugin http://medleyweb.com/web-dev/15-useful-jquery-parallax-plugins-and-tutorials/

JQuery.load breaks other javascript -

when use jquery.load, breaks other javascript libraries. receive error: typeerror: $.dotimeout not function when not use jquery.load it, works fine. i don't understand causes happen. seems couldn't find function javascript file rendered on source code. scripts <script type="text/javascript" src="/assets/js/modernizr-1.7.min.js"></script> <script type="text/javascript" src="/assets/js/jquery.tmpl.js"></script> <script type="text/javascript" src="/assets/js/jquery.ba-dotimeout.js"></script> <script type="text/javascript" src="/assets/js/test1.js"></script> <script type="text/javascript" src="/assets/js/test2.js"></script> inside test1.js $.dotimeout("hoverout"); inside test2.js $(".test").load("/test.aspx?param=" + somevalue); jquery.ba-dotimeout.js library test1....

python - no module named disco.core -

i've been following tutorial here: http://discoproject.org/doc/disco/start/install.html and have been succesful point run script. error: no module named disco.core i have installed disco according instructions above, doesn't seem have installed python library. i have tried installing using conda, pip, , easy_install without luck.. anyone have ideas? run make install , should install disco libs in standard location (site-packages or dist-packages).

Jxplorer certificate for ldap -

i don't know if familiar tivoli directory server (ldap) guess there more or less same in every ldap software. so, there setting ssl authentication can serverclientauth , serverauth. serverauth sufficient server provide certificate , client (jxplorer) accepts connect. serverclientauth except certificate provided server client needs have certificate on server. in setup have serverclientauth setting. wondering if possible jxplorer provide client certificate ldap server. any thoughts welcome. thanks. yes possible, , there menu provided purpose, lets define keystore, truststore, , various other ssl things.

Creating static, nested associative arrays in Java -

i have data model represent in java class, defined nested associative array. want able create instance of object , either reference key-value pairs name, or iterate on them. if going in python or javascript, nested associative array might this: sandwiches = { "ham sandwich": { "bread": "white", "meat": "ham", "condiment": "mustard" }, "blt": { "bread": "rye", "meat": "bacon", "condiment": "mayo" }, ... } is there quick , easy way create object in java? assume nested hashmap looking for, there not seem simple one- or two-lined method creating object using native java libraries. if there not exist way standard java libraries, 3rd-party tools ideal this?

objective c - NSData subStringFromIndex: Equivalent -

i'm receiving stream of nsdata characters around @ least 50 characters. usually, try , convert nsstring , use substringfromindex: selector, seems nsstring null terminating (correct me if i'm wrong) , i'd rather skip data / string conversion. know if there way charecter @ specific index in nsdata? example, data returned is: <12345678 9abcdefg hjiklmno> lets 7 , 8 out, , 2 alone. 7 , 8, i've looked trying this: nsdata *datatrimmed = [data subdatawithrange:nsmakerange(7, -19)]; works charm. issue is, stream going different length. 100 characters or 50, know 2 values need located @ 42nd , 43rd spot. have example of or know best way this? i wonder code negative length not crash. to 2 bytes @ position 42, 43, use nsdata *datatrimmed = [data subdatawithrange:nsmakerange(42, 2)];

arrays - java all values int[] 0 -

for minigame written in java, have main level , background level. player able walk in mail level, , background level solely decoration. ive written method checks visible background tiles, , puts coordinates of these tiles in int[][][]. array threedimensional, because background threedimensional. because background not visible, thought save quite processing time first checking whether single background tile visible. in other words, checking whether array containing visible background tiles, has value written in slot. when tile visible, coordinate in array becomes 1, , otherwise, remains @ default value (0 thought). guys know way check whether array contains value, program doesn't have browse through every single slot, 60 times second? if don't want go through whole array every time, keep flag or similar tells whether there visible. even though should have plenty of computing power go through array 60 times per second :)

fine granularity nanosleep not power efficient in c++ program on linux -

i trying call sampling function periodically within c++ thread on linux machine. restart function after short period, ideally 1 msec, i'm finding power (in watts) consumed 1 msec period prohibitively high: system runs @ double power level when period 5 msec. keeping power low major concern functionality want. specifically, void* loop_and_sample(void* arg) { while(1) { sample(); nanosleep((struct timespec[]){{0,1000000}}, null); } } takes 2x power of: void* loop_and_sample(void* arg) { while(1) { sample(); nanosleep((struct timespec[]){{0,5000000}}, null); } } i have determined difference in power usage of sampler @ 2 frequencies negligible, , power consumption comes sleep call. is, if comment out sample() line in both snippets above, second still takes half power. ideas how might able reduce power consumed sleep call? fyi, i'm running ubuntu 3.2.0 on 24-core intel xeon , search of /boot/config frequency shows following: ...

Creating Sprite Unity3d -

please tell me, easiest way programmaticaly create tk2dsprite in toolkit2d(unity)? have .png image in assets/image sprite must created. want create sprite, , show on scene. i not @ computer try (c#): string spritename = "spriteinspritecollection"; gameobject spriteobject = new gameobject(); tk2dsprite spritecomponent = spriteobject.addcomponent<tk2dsprite>(); spritecomponent.setsprite(spritename); i test , see if component created , initialized sprite before adding object can't right now, points in right direction though. edited include improvement slxs.

iphone - Can't deploy iOS application to phone -

so made first iphone application, , wanted test on actual device. clicked in xcode's organizer "use development," , accidentally typed wrong password developer's account. whenever try test on phone, get: code sign error: identity 'iphone developer' doesn't match valid, non-expired certificate/private key pair in keychains and can't seem figure out how fix that. tried doing provisioning profiles , says team small. how fix this? thank you! i did negative test , deleted of provisioning profiles on development iphone (settings->general->profiles, remove 1 one). having on laptop proper profiles , iphone without profiles confirm can test , run app on device run project on device. so problem not because accidentally made typo in password more project' building properties not correct and/or provisioning profile not matches app's settings. you can find many info how handle such situations here @ so or other places lik...

Android Facebook Login Prolem -

i followed steps in website: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/ the result on simulator correct(it show "hello + name"). but when test application on phone, it show nothing. can tell me what's wrong,thanks!! following code: @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // start facebook login session.openactivesession(this, true, new session.statuscallback() { // callback when session changes state @override public void call(session session, sessionstate state, exception exception) { if (session.isopened()) { // make request /me api request.executemerequestasync(session, new request.graphusercallback() { // callback after graph api response user object @override public void oncompleted(graphuser user, res...

for loop - How to partition large Hive table with many categories -

i want partition table in hive every unique item in row creates partition. there ~250 partitions 4 billion row table to loop or distinct. here thoughts in code (which have not worked) alter table mytable add if not exists partition( mycolumn = distinct mycolumn); or there kind of loop in hive? require udf? hive answer preferable if possible. thanks. just use dynamic partitions https://cwiki.apache.org/confluence/display/hive/tutorial#tutorial-dynamicpartitioninsert it partition creation on go

jquery - Switching between radio buttons causes duplicate coordinates -

i'm running bit of pickle. have working tool utilizes jquery's plugin gmap3 , allows user select between writing json array, dropping pins or address. tool spits out json array <textarea> it's easy grab information later. problem duplicate coordinates created when "address" selected , user decides select option "drag n' drop" go "address" , type new address in. appreciated! jsfiddle scenario: click on address in selection. type in address in input , click add. click on drag n' drop in selection select address again. type in different address time in input, click add , watch duplicate coordinates appear in <textarea> code: $(document).ready(function() { //////// gmap3 json array //////// var mapopts = { maptypeid: google.maps.maptypeid.roadmap, maptypecontrol: true, maptypecontroloptions: { style: google.maps.maptypecontrolstyle.dropdown_menu }, navigationcontrol: true, ...

jquery - How to create an array from files in a folder? -

arr01 =[ "01.png", "02.png", "03.png", "04.png", "05.png"...]; arr02 =[ "01.png", "02.png", "03.png", "04.png"...]; arr03 =[ "01.png", "02.png", "03.png", "04.png"...]; these images files in folders named 01, 02, 03... i need create arrays managing images in slider. is possible telling: give me file names in folder 01 , , create array them ? it needs done server-side, i'd suggest writing small service returns json structure representative of want display. it's not hard write recursive algorithm that'll convert directory tree json tree. advantage instead of having arr01 , arr02, , etc. you'll have this: { root: '/media', items: [ 'image.png', 'image2.png', 'vacation': [ 'image3.png', //you idea ] ] } that'll lot easier work on client side ge...

c++ cli - Common pattern when using arrays in C++/CLI -

i experienced c++, began learn c++/cli. notice following pattern lot: array<string^>^ x; how guys think this? way interpret is, array of strings , want them on managed heap , why use string^, want vector on managed heap , why have array<something>^. correct? c++cli ref class must live on managed heap. actual non-managed heap instances blocked. both string , array ref class types, must live on managed heap. c++, in order remind user these garbage-collected pointer types, , not literals or traditional pointer types, requires end types ^ . while redundant (all instances of array<> array<>^ -- hence in c# there no such ^ token), reminder managed type , not normal type helps when mix managed , unmanaged code.

php - Do-While Loop with Multiple Conditions -

can do-while loop have multiple conditions? if so, can't figure out why code below failing on first condition. functions used... function gcf($a,$b) { $a = abs($a); $b = abs($b); if( $a < $b) list($b,$a) = array($a,$b); if( $b == 0) return $a; $r = $a % $b; while($r > 0) { $a = $b; $b = $r; $r = $a % $b; } return $b; } function factors($n){ $factors_array = array(); ($x = 1; $x <= sqrt(abs($n)); $x++) { if ($n % $x == 0) { $z = $n/$x; array_push($factors_array, $x, $z); } } return $factors_array; } code... $a = $b; do{ $a = mt_rand(8, 100); $a_factors_array = factors($a); $b = mt_rand(8, 100); $b_factors_array = factors($b); } while ($a == $b && count($a_factors_array) < 4 && count($b_factors_array) < 4 && gcf($a, $b) == 1); echo $a . '<br>'; echo $b . '<br>'; echo count($a_factors_array) . '<br>'; echo count($b_factors_array)...

core data - How can I change section ordering with NSFetchedResultsController? -

i'm setting nsfetchrequest following sort descriptor: [sortdescriptors addobject:[nssortdescriptor sortdescriptorwithkey:@"color" ascending:yes]]; i'm setting sectionnamekeypath nsfetchedresultscontroller "color" attribute. the results sorted sections based on color, expect. it's valid "color" attribute empty string "" objects. grouped in first section, since sort before other names. however, i'd them appear final section, not first section, without affecting search order of remaining objects. for example, sections might be: "" "green" "red" "yellow" but i'd sections in order: "green" "red" "yellow" "" is there way write sort descriptor behavior? i've been unable come myself. a sort descriptor (sqlite based) core data fetch request can use standard comparator methods , use (persistent) attributes stored in...

Can Python Create 2D Games? -

is possible make 2d games using python? if got links 2d game used python create it? thinking of learning python thought should ask guys if can create 2d games before start. yes, check out http://pygame.org it's pretty popular 2d library python.

asp.net mvc - TypeError $(...) is not a function when using a jquery plugin -

i got 1 jquery experts. i downloaded simple jquery plugin convert table csv. here source code... http://www.kunalbabre.com/projects/table2csv.js now, created local jscript file. jquery.table2csv.js. added page right after jquery <script type="text/javascript" src='@url.content("~/scripts/libs/jquery-1.6.3.min.js")'></script> <script type="text/javascript" src='@url.content("~/scripts/jquery.table2csv.js")'></script> it's loading correct (200 ok) according firebug. in 1 of views, have following code... <script> $(document).ready(function () { $("#exporttocsv").click(function (event) { event.preventdefault(); alert('button clicked!'); $('#reportdatatable').table2csv(); }); }); </script> the trigger fires click event, no problem, following error. typeerror: $(...).table2csv not function ...

logical operators or vs || (double pipe) in php -

this question has answer here: logical operators, || or or? 7 answers i've used || (double pipe) if (($a == $b) || ($a == $c)) { } , or do_this() or do_that(); . why not if (($a == $b) or ($a == $c)) { } or do_this() || do_that(); ? is there reason use of these 2 logical operators or personal preference? the same applies && vs and , use && . the "spelled out" operators and , or have lower precedence, lower assignment, may use them avoid having write parentheses in many places. example: $d=$a||$b , $c equivalent ($d=$a||$b) && $c they more readable in many contexts.

sockets - Pipe raw HTTP stream to PHP r/w stream -

i wondering if possible @ http request made browser towards php running apache module read- , writable stream. i did research , testing , appears standard streams ://stdin/-out/-error , ://input may available running php in cli mode [link] . what want reading raw http request. also, should happen in read/write stream can write bytes directly response request. possible? other running php in cli, it's not possible achieve reading/writing raw streams way.

c# - How do I unit test this custom commandlet -

i unable figure out how unit test if commandlet fail, if no arguments provided it. [cmdlet(verbscommon.move, "someresource")] public class movesomeresource : cmdlet { private int _id; [parameter(position = 0, mandatory = true)] [validatenotnullorempty] public int id { { return _id; } set { _id = value; } } protected override void processrecord() { string text = string.format("move resource {0} ", this._id); //do if (shouldprocess(text, action)) { //do processing } } } i tried following method but, not fails due validatenotnullorempty error rather executes part in //do processing , fails there . [testmethod] public void testmovebluh() { movesomeresource cmd = new movesomeresource(); ienumerator result = cmd.invoke().getenumerator(); try { result.movenext(); } catch (exception e) { assert.isinstanceoftype(e, typeof(argumentexception)); } } ok, think see issue. parameter int, int's aren't null, ...

java - Acquire method reference in JSF EL -

in jsf 2 have declared function inspect takes 1 argument of type java.lang.reflect.method , based on argument performs annotation inspection , returns true or false . catch want call function inspect jsf el able modify ui according return value not able reference of target method pass argument of function, ask how it? example package some.pkg; @managedbean( name = "someclass" ) public class someclass { @myannotation public void somemethod( string arg1, integer arg2 ) { /* ... */ } } jsf function declaration <function> <function-name>inspect</function-name> <function-class>some.pkg.inspector</function-class> <function-signature>boolean inspect(java.lang.reflect.method)</function-signature> </function> desired invocation jsf, doesn't work <h:outputtext value="somemethod annotated @myannotation" rendered="#{inspect(someclass.somemethod)}" /> ac...

SQLite on Android doesn't insert properly -

i making android app learn sqlite databases. have function should write user's movement data accelerometer database. database created with: db.execsql("create table if not exists data(id integer primary key autoincrement, "+ "lat integer, long integer, "+ "movement real, "+ "time text);"); and function writes db called every 2 seconds: void inserttable(float mov) { db.begintransaction(); try { // part gets current time calendar = calendar.getinstance(); string date = now.get(calendar.hour_of_day)+":"+now.get(calendar.minute)+":"+now.get(calendar.second)+ "."+now.get(calendar.millisecond)+" "+now.get(calendar.day_of_month)+"/"+now.get(calendar.month)+ "/"+now.get(calendar.year); db.execsql("insert data(movement ,time) values ("+ mov+",'"+date+"');"); c...

javascript - Create a route using a list of coordinates in Google Maps -

Image
i have list of lat,lon coordinates result of tracking bus. i'm showing route using polyline create line connect "the dots" because of accuracy these dots aren't street, , when zoom in more obvious. what can show route street? this have right (there 2 lines because bus did 2 turns. won't show in final product) and need. thanks help. search 'snap polyline road using google maps api v3' similar discussions. there doesn't appear straightforward api service , need reduce route significant changes in direction rather every wiggle. you might add star issue in 'google maps api bug reports , feature requests' database http://code.google.com/p/gmaps-api-issues/issues/detail?id=3824 , possibly add new issue since problem different

java - Adding JPanel to JFrame? -

i'm trying add jlabel jpanel jframe. set border jpanel, see on jframe small black square in center of frame. whatever can't change size or location of it. please help. start main = new start(); random random = new random(); jframe mainframe = new jframe("mainframe"); jpanel mainpanel = new jpanel(); jlabel welcomelabel = new jlabel(); mainframe.add(main); mainframe.setlayout(new gridbaglayout()); mainframe.setdefaultcloseoperation(jframe.exit_on_close); mainframe.settitle(names[random.nextint(names.length)]); mainframe.pack(); mainframe.setvisible(true); mainframe.setsize(mainframex, mainframey); mainframe.setresizable(false); mainframe.setlocationrelativeto(null); mainframe.add(mainpanel); mainpanel.add(welcomelabel); mainpanel.setborder(new lineborder(color.black)); mainpanel.setsize(new dimension(200, 200)); welcomelabel.setfont(new font("verdana", 1, 20)); welcomela...