Posts

Showing posts from September, 2015

c++ - Collision Detection and Time Complexity: How do I make checking for collisions easier? -

i'm trying write program handles detection of various objects. objects have origin, width, height, , velocity. there way set data structure/algorithm every object isn't checking every other object? some sample code of problem i'm trying avoid: for (int = 0; < ballcount; i++) { (int j = + 1; j < ballcount; j++) { if (balls[i].colliding(balls[j])) { balls[i].resolvecollision(balls[j]); } } } as mentioned other answer(s), can use quadtree structure make collision detection faster. i recommend geos open-source c++ library, has quadtree implementation. here docs quadtree class . so pseudo code this: quadtree quadtree; // create , populate quadtree. // change whenever balls move. // here's intersection loop: (int i=0; i<ballcount; ++i) { envelope envelope = ...; // bounds (envelope) of ball std::vector<void*> possiblyintersectingballs; quadtree.query(envelope, possiblyintersectingballs); // loop on members of possiblyintersectingballs check // if int...

r - Learning to understand plyr, ddply -

i've been attempting understand , how plyr works through trying different variables , functions , seeing results. i'm more looking explanation of how plyr works specific fix answers. i've read documentation newbie brain still not getting it. some data , names: mydf<- data.frame(c("a","a","b","b","c","c"),c("e","e","e","e","e","e") ,c(1,2,3,10,20,30), c(5,10,20,20,15,10)) colnames(mydf)<-c("model", "class","length", "speed") mydf question 1: summarise versus transform syntax so if enter: ddply(mydf, .(model), summarise, sum = length+length) i get: `model ..1 1 2 2 4 3 b 6 4 b 20 5 c 40 6 c 60 and if enter: ddply(mydf, .(model), summarise, length+length) same result. now if use transform: ddply(mydf, .(model), transform, sum = (length+length)) i get: model class length speed sum 1 e 1 5 2 2 e 2 10 4...

python - How to escape a ' within a string? -

i have little script creates insert sql statement me. for postgresql need wrap values inserted within 2 single quotes. unfortunately of value strings inserted contain single quote, , need escape them automatically. for line in f: out.write('(\'' + line[:2] + '\', \'' + line[3:-1] + '\'),\n') how can make sure single quote (e.g. ' ) inside line[3:-1] automatically escaped? thanks, update: e.g. line ci|cote d'ivoire fails due ' update 2: i can't use double quotes in values, e.g. insert "app_country" (country_code, country_name) values ("af", "afghanistan") i error message: error: column "af" not exist this works fine: insert "app_country" (country_code, country_name) values ('af', 'afghanistan') as described in pep-249 , dbpi generic interface various databases. different implementations exist different databases. postgres there psycopg . docs: c...

c# - Inheritance vs varying instances? -

if modelling various brands of cars use inheritance hierarchy, or varying constructor parameters? what general rule whether relate objects using inheritance, or re-using same class? for cars new car("porsche","991","3.8") or have overall abstract car superclass, abstract subclass manufacturers "porsche" , possibly class each model of porsche? if have few properties shared cars (or methods act on object), , unique properties (or methods) each make/model, you'd want use inheritance. otherwise, varying instances fine. let's want these properties cars: make model year of doors in case, wouldn't want create class hierarchy, because doesn't buy anything. instead, if had 2 "types" of cars: regular , race-car, , race-car enable nitrous oxide (presumably method this), you'd want car class, regularcar , racecar inheriting it. if you're afraid of having pass same parameters constructor time, can create stat...

PHP Preg_replace() function -

how use preg_replace function replace /c83403.403/ example: https://startimage.ca/c83403.403/ahmedmynewpix.jpg another example: https://startimage.ca/c2.3403.403/ahmedmynewpix2.jpg it start /c..../ want replace "" i trying following not working $str = '/c..../'; $str = preg_replace('/+[0-9]', '', $str); do mean this? $str = 'https://startimage.ca/c83403.403/ahmedmynewpix.jpg'; $str = preg_replace('|/c[0-9.]+|', '', $str); echo $str; # https://startimage.ca/ahmedmynewpix.jpg' ... or $str = preg_replace('|/c[0-9.]+|', '/c', $str); echo $str; # https://startimage.ca/c/ahmedmynewpix.jpg' the point replace starting /c , containing either digits or dot symbol ( . ) - either empty space or /c string, depending on need. )

android - Reading ActivityManager-logs on a Jelly Bean device? -

jelly bean has removed ability read logs of other apps (according this i/o talk), sensible security improvement. however, need read activitymanager -logs app work (to see app starting). this, using private static final string clearlogcat = "logcat -c"; private static final string logcatcommand = "logcat activitymanager:i *:s"; //... which no longer works, can read own application's logs in jelly bean. there alternative solution finding out when app starting (apart root)? understand why shouldn't able read other applications' logs (kind of - should other developers' resposibility make sure no personal information logged, not mine being prevented reading log), don't understand why activitymanager , framework class, included in policy... thanks, nick there extensive discussion of issue going on here . unfortunately, it's "expected behavior" , such won't fixed. current solution (for reading logs within application on jb , ...

python - Tuple of objects that, if referenced directly, returns first object -

i want modify 1 of api methods returns object. think should return tuple of objects. don't want change way people call api method. there way return tuple of objects can referenced directly first object? if change function returned object instead return tuple, callers of function have changed. there no way around that. either change callers extract first object, or unchanged code have tuple used have object.

python - Better way to remove statistical outliers than this? -

this code works. can't feel it's hack, "offset" part. had put in there because otherwise index values in deletes shifted 1 every time del operation. # remove outliers > devs # of std deviations devs = 1 deletes = [] num, duration in enumerate(durations): if (duration > (mean_duration + (devs * std_dev_one_test))) or \ (duration < (mean_duration - (devs * std_dev_one_test))): deletes.append(num) offset = 0 delete in deletes: del durations[delete - offset] del dates[delete - offset] offset += 1 ideas on how make better? build list of keepers iterate on list: def iskeeper( duration ): if (duration > (mean_duration + (devs * std_dev_one_test))) or \ (duration < (mean_duration - (devs * std_dev_one_test))): return false return true durations = [duration duration in durations if iskeeper(duration)]

python - Method overloading decorator -

i'm trying write decorator provides method overloading functionality python, similar 1 mentioned in pep 3124 . the decorator wrote works great regular functions, can't work methods in class. here decorator: class overload(object): def __init__(self, default): self.default_function = default self.type_map = {} self.pos = none def __call__(self, *args, **kwargs): print self try: if self.pos none: pos = kwargs.get("pos", 0) else: pos = self.pos print args, kwargs return self.type_map[type(args[pos])](*args, **kwargs) except keyerror: return self.default_function(*args, **kwargs) except indexerror: return self.default_function(*args, **kwargs) def overload(self, *d_type): def wrapper(f): dt in d_type: self.type_map[dt] = f return self return wrapper when attempt implement this: class myclass(object): def __init__(self): self.some_instance_var = 1 @overload def print_first_item(self, x): return x[0], self.some_instance_var @print_first_item.overload(str) def print_fi...

PHP variable with minus in -

i'm modifying script want server stats, i've put server key 1 of variables. fear variable can't have minus within them. true? see line 3. // convert lists json $postdata=array(); $postdata['id']="534f7035-cef8-48aa-b233-8d44a0956e68"; // run post request via curl $c2=curl_init('http://api.bf3stats.com/'.$platform.'/server/'); curl_setopt($c2,curlopt_header,false); curl_setopt($c2,curlopt_post,true); curl_setopt($c2,curlopt_useragent,'bf3statsapi/0.1'); curl_setopt($c2,curlopt_httpheader,array('expect:')); curl_setopt($c2,curlopt_returntransfer,true); curl_setopt($c2,curlopt_postfields,$postdata); $id=curl_exec($c2); $statuscode=curl_getinfo($c2,curlinfo_http_code); curl_close($c2); if($statuscode==200) { // decode json data $id=json_decode($id,true); } else { echo "bf3 stats api error status: ".$statuscode; } your code work fine, however; since you're not parsing variables in string, might use single quo...

An academic query about T4 templates -

ok, i'm thinking little ahead here in current project, apologize how vague question going be. possible in 1 project of solution have t4 template references 1 of other assemblies in solution , inspects exported types of other assembly , uses metadata build other code? don't need reference types in assembly directory, need able list of of them derive particular base class , metadata them. i'm thinking of doing objects built common base class , dumped database nhibernate easy way generate dto classes them throwing @ client during ajax calls. i'm not looking absolutely perfect solution, 1 gets lot of easy cases out of way. again, don't have specific example. i'm few days out running problem head-on, occurred me option might cover lot of cases might run into. thoughts? yep, should fine - can use <#@ assembly #> directive , use $(solutiondir) , other vs macros starting point navigate other project's output. can use reflection read metadata you're ...

Scala Pattern Matching Compiler Warning -

i caused bug in code tougher find have liked, , i'd ideally avoid in future. expected scala compiler have warned me error (unless i'm missing something). i've reduced trivial case: vector.maybegetvector match { case v:vector => true case _ => false } case class vector(x:int, y:int) object vector { def maybegetvector : option[vector] = some(new vector(1,2)) } the reason used wildcard instead of none fall through want match on subtype of returned option . i expecting compiler warning, it's easy reason first case statement contains unreachable code. option[vector] can't subtype of vector . the strange part if add following case statement: case i:int => false it raises error , tells me option[vector] required. is there way protect against programmer error in way, outside of naming conventions. things can ever match against option some/none/null . feel i'm missing obvious. if define vector class final modifier, you'll "pattern ty...

ios - How do I remove goBack events on UIButtons in UIPageViewControllers? -

in xcode project (ios 5.1) have been using uipageviewcontroller , noticed when tap on button automatic action send goback event , flip page previous index. i bewildered because checking on responders uibutton haven't been associated goback event or other event matter. any clues on how remove behavior? ok, after more searching realized happening. apparently uibutton isn't throwing goback event; since button in left field of uipageviewcontroller subview uitapgesture captured on region , initiates goback event. the same thing happen if uibutton on right side of uipageviewcontroller , cause goforward event instead. the details on how fix problem in question: uipageviewcontroller gesture recognizers

yii - using CActiveDataProvider to display group by MYSQL record -

Image
please need quick right now. here question i have table several columns. using yii framework display data want group record in way column 1 column2 column3 column4 1 2 3 4 80 3 1 100 30 3 1 60 50 3 0 10 90 2 3 40 100 2 1 80 so want query table display column2 , column3, group column2. having issues that, column2 returns 2,2 - 3,3 , group record column3 under each of duplicated column2 my result should display in way: ........................................................................ column2 -- 2 .1 .3 ......................................................................... column2 -- 3 .0 .1 controller:: protected function displaybycategory() { //$model = new mymodel; $criteria= new cdbcriteria(); $criteria->distinct = true; $criteria->group = 'column2,column3'; $criteria->order = 'column2'; //$dataprovider=new cactivedataprovider('mymodel' ); $dataprovider=new cactivedataprovider('mymodel', array( 'criteria'=>$cr...

actionscript 3 - reference variable AS3 -

i trying create simple as3 code in flash professional cs6 references variable. example: var1:int = 1; varref = "var1"; (this "reference" variable, ofcourse not how it's done in as3) if (var1 == 1) { varref = 50 } if run, try make string variable varref "var1" int of "1'. want reference variable, not variable of it's own. a simple example of how great. (from know, object may needed, simple object example of situation great.) i'm using class creating references : https://github.com/turbosqel/as3supportlib/blob/master/as3supportlib/src/turbosqel/data/lvar.as its simple use , : public var item:string = "some str"; {...} var ref:lvar = new lvar (this,"item"); trace(ref.value);// return : "some str" trace("my ref " + ref ); // return : ref str // can change on runtime : item = "new value"; trace(ref.value); // return : new value same thing can other data type .

html - Make a 3D button with rounded edge -

i developing website in want implement 3d buttons rounded edges.so need create css file.i search alot 3d button nothing has worked me yet. have @ http://css3button.net/