Posts

Showing posts from May, 2015

java - execute an action from a javafx menu item and keeping gui and action in separate files -

who: work county ambulance service. have forty ambulances , 2 hundred fire apparatus. what: asking write compute program in java. have gui constructed in javafx scene builder 2.0. using netbeans code application. enclosed simple code gui. question in 2 parts; question 1.) have analysis menu expected call volume menu item. have code reaches database , pulls out information , generates poisson frequency distribution. how marry 2 things together. in other words, when user clicks menu item should fire off code. how attach code menu item? question 2.) perhaps not question, keeping action code in separate .java file. reason doing keep separate gui code. think more manageable have pieces unique things. there special need tie separate java file gui? java file action event go (fxmldocumentexplorer.java or javafxapplication2.java)? when: hoping accomplished before 9 october 2015 where: javafx scene builder 2.0 , netbeans 8.02 on windows machine. jdk 8. why: have lot of databas...

how to login and sign up in android using web service in android -

how login , sign in android using web service . see below: first name second name address email sign (button) need code of sign using api in android you can try jsoup library. java library support web services. see: http://jsoup.org

Google Places Radar Search Leaving Out Some Results (not referring to detail information) -

when doing radar search specific place type (in case "shoe_store") api not returning (within 200 limit) places type "shoe_store" in radius. obtaining beyond radius, leaving out within. more following api search 1 i'm looking @ now: api call: https://maps.googleapis.com/maps/api/place/radarsearch/xml?location=39.0923384,-76.8564899&radius=28967&types=shoe_store&key=apikey using radius of 28,967 should "shoe_stores" within 18 mile radius. looking ensure "shoe show" , "shoe dept" of there 7 when 1 simple "shoe show near 14708 baltimore ave laurel, md 20707" in regular maps.google.com site. however, when using radar search 1 of them shows while other, further out, shoe stores show up. am missing in api call or api prioritize results sees fit, skipping , not staying within specified radius?

game physics - Cocos2d-x 3 - Disable collision between two bodies and detect when them separate each other -

Image
i'm developing cocos2d-x game (version 3.8). game uses chipmunk physics , has static body works interruptor. interruptor enabled when body on it. interruptor disabled when bodies separate each other. i want to: moving body don't collision interruptor. has cross interruptor no bounce i want detect when moving body separates interruptor my first approach implementing oncontactbegin method. return false when 2 bodies in touch. way body crosses interruptor , not bounce. the problem oncontactseparate method not called, because contact did not happen. if return true in oncontactbegin method, oncontactseparate called , can detect it. problem body not cross interruptor, bounces. [edit] more info this scenario 2 sprites separated. ball can move , interruptor static body. ball on interruptor. this scenario 2 sprites in contact , object1 (the ball) on interruptor. want detect 2 sprites separate each other. any appreciated! it seems me using box2d with...

django - DjangoRestFramework - How to access other fields of a OneToOneField reverse relationship using a model serializer? -

i using default user model , extending userextended model: class country(models.model): countryname = models.charfield(max_length=50, unique=true) countrycode = models.charfield(max_length=10, unique=true) class userextended(models.model): user = models.onetoonefield(user, related_name="userextended") country = models.foreignkey(country) i trying follow documented here: http://www.django-rest-framework.org/api-guide/relations/#reverse-relations this userserializer: class userserializer(serializers.modelserializer): def __init__(self, *args, **kwargs): super(userserializer, self).__init__(*args, **kwargs) # call super() field in self.fields: # iterate on serializer fields self.fields[field].error_messages['required'] = 'enter valid %s.'%field # set custom error message class meta: model = user fields = ('username', 'password', 'email', 'us...

javascript - Don't let the parent website, get info from my iFrame -

i have make iframe manage user's sensible information. need parent page not able information it. can recommend me achieve goal?. saw how obfuscate javascript code, not enough need impossible have access website iframe's values inside fields user fill up. for example try making own frame , web test security , if put on web: iframename.document.getelementbyid("idtextfield").value; text client filled, thats want prevent, impossible (or difficult) web data of fields have in iframe. thank all. by way im using html, js , php all modern browsers prevent site getting iframe content doesn't belong it. security feature prevent hacking. for example, if log bank's website , go site includes bank in iframe, may see bank page in iframe, third party site still not able read it. furthermore, bank not appear in frame begin because many sites (including stackoverflow) prevent iframes displaying them . assuming iframe isn't in same domain containing ...

rest - Drools - Response XML from multiple rule execution -

i have below 2 rules: global response myresponse; rule "rule1" when loan(processid == "1") myresponse.setruleid("rule1"); myresponse.setpmtstatus("valid"); end rule "rule2" when loan(amount > 1000) myresponse.setruleid("rule2"); myresponse.setpmtstatus("invalid"); end when access drools through rest sending below request xml, according data inserted, both rules should fire. <batch-execution lookup="testsession"> <set-global identifier="myresponse" out-identifier="response"> <com.sample.response></com.sample.response> </set-global> <insert out-identifier = "loan"> <com.sample.loan> <loanid>11112222</loanid> <processid>1</processid> <amount>2000.00</amount> </com.sample.loan> </insert> <fir...

Multiplying array elements with Javascript -

i'd know fastest , efficient way multiply array elements using javascript. var array = ["1", "2", "3", "4"]; so outcome total 10. first, values strings, not numbers, first thing make them numbers: array.map(number) then multiply .reduce array.map(number).reduce(function(product, value) { return product * value; }); edit — comment wisely notes * operator try convert operands numbers anyway. explicit conversion numbers, add filter see if there nan values produced, nan spreads cancer wouldn't matter. consider numeric conversion optional. now, in general , if getting array of numbers-as-strings api, i'd inclined explicit conversion, because in sense means there's wrong design of api. i'd prefer isolate "interesting" code weird stuff that.

python 3.x - Get object instances in template using ModelMultipleChoiceField/CheckboxSelectMultiple in Django -

with code managed object's pk , name (return value of __str__ method), need access object instance (i need of methods/fields in template). how can that? {% value, name in form.stuffs.field.choices %} {{ value }} + {{ name }} {% endfor %}

javascript - jQuery added form elements cannot be selected -

i apologise description if it's not fitting. hard describe what's going on. i have set jsfiddle here . function addnewform() { $('body').html(function () { //display log in form return "<input type=\"text\" placeholder=\"word or phrase\" id=\"prompt\" />\n" + "<textarea id=\"answer\" placeholder=\"answer text\"></textarea>\n" + "<input type=\"button\" id=\"addnew\" value=\"add this!\" />\n" + "<p>&nbsp;</p>"; }); } $("#addnew").click(function () { $("p").html("add new clicked<br />"); }); $("a").click(function () { addnewform(); }); is syntax correct? reason, $("#addnew").click works when generated outside of own function button stops working since have tidied code , placed within own f...

SBT: Get dependendOn projects as jars -

i have project declaration this lazy val myproject = (project("name", file("path")) dependson(project1, project2)) is there way project1 , project2 jar files , them path? need them to copy in file system when compile myproject i found projectdependencies contains of them moduleid. (package in compile in project1).value and project2.

python - Unstable behaviour of has_key shelve method -

i've been using shelve library python (not in multiprocessing environment), , i've been observing unstable behaviour when using has_key() method. returns true , false, when know key exists in shelve. usual cause of such behaviour? import shelve some_key = 'not relevant' s = shelve.open('cache.db') if s.has_key(some_key): var = s[some_key] print 'found key', some_key s.close() note: python 2.7, ubuntu 14.04 in vm virtualbox, running in i7 x86-64bit

python - Logical operators with lists -

i have problem: have 2 lists pipe_sizes = [15,15,22,15,32,45] flow_rate = [0.1,0.3,1,2,0.4,1.5] i use logical operators change list pipe_size like: if flow_rate <= 0.2 pipe size 15 if flow_rate > 0.2 , <= 1 pipe size 22 if flow_rate > 1 , <=1.9 pipe size 32 if flow_rate > 1.9 pipe size 45 how can it? pipe_sizes irrelevant generating ouput because possible flow rate / pipe size combinations covered in list of conditions. can generate result directly: def flow_rate_to_size(rate): if rate <= 0.2: size = 15 elif 0.2 < rate <= 1: size = 22 elif 1 < rate <= 1.9: size = 32 else: size = 45 return size flow_rates = [0.1, 0.3, 1, 2, 0.4, 1.5] pipe_sizes = [flow_rate_to_size(rate) rate in flow_rates] print(pipe_sizes) output: [15, 22, 22, 45, 22, 32]

png - Change the format of an Image in java without saving -

i read image , change format without saving it. for example can read image this bufferedimage img=imageio.read(new file(filename)); then want change format of img , example jpeg png. way found use imageio.read write , read new image, seem efficient way it. when "read" image via bufferedimage img=imageio.read(new file('myimage.png')); you not reading decoding it, i.e., transforming raw bytes in (say) png format "raw" format aplication or api can manipulate (or display) - in case, bufferedimage . once done, fact image came png file forgotten. read png , save jpeg need decode (as png) , code (as jpg). i read image , change format without saving it. the "format" of image (in png/jpeg sense) gives way of packing image in sequence of bits. so, desire makes little sense. @ most, store bits in memory (what for?), same "saving it" (to memory instead of disk).

java - What is a NullPointerException, and how do I fix it? -

what null pointer exceptions ( java.lang.nullpointerexception ) , causes them? what methods/tools can used determine cause stop exception causing program terminate prematurely? when declare reference variable (i.e. object) creating pointer object. consider following code declare variable of primitive type int : int x; x = 10; in example variable x int , java initialize 0 you. when assign 10 in second line value 10 written memory location pointed x. but, when try declare reference type different happens. take following code: integer num; num = new integer(10); the first line declares variable named num , but, not contain primitive value. instead contains pointer (because type integer reference type). since did not yet point java sets null, meaning "i pointing @ nothing". in second line, new keyword used instantiate (or create) object of type integer , pointer variable num assigned object. can reference object using dereferencing operator . (a dot...

java - Comparing integers and creating the smallest integer possible from the digits of the given integers -

i need write following method: accepts 2 integer parameters , returns integer. if either integer not 4 digit number method should return smaller integer. otherwise, method should return 4 digit integer made of smallest digit in thousands place, hundreds place, tens place , ones place. cannot turn integers strings, or use lists, or arrays. for example biggestloser(6712,1234) returns 1212 example biggestloser(19,8918) returns 19 here's how i've started write it: public static int biggestloser(int a, int b){ if(a<9999 || b<9999){ if(a<b) return a; else if(b<a) return b; } int at=a/1000; int ah=a%1000/100; int an=a%100/10; int ae=a%10; int bt=b/1000; int bh=b%1000/100; int bn=b%100/10; int be=a%10; if(at<bt && ah<bh && an<bn && ae<be) return at*1000+ah*100+an*10+ae; else if(at<bt && ah<bh && an<bn &...

compression - Create a compress function in Python? -

i need create function called compress compresses string replacing repeated letters letter , number. function should return shortened version of string. i've been able count first character not others. ex: >>> compress("ddaaaff") 'd2a3f2' def compress(s): count=0 in range(0,len(s)): if s[i] == s[i-1]: count += 1 c = s.count(s[i]) return str(s[i]) + str(c) here short python implementation of compression function: def compress(string): res = "" count = 1 #add in first character res += string[0] #iterate through loop, skipping last 1 in range(len(string)-1): if(string[i] == string[i+1]): count+=1 else: if(count > 1): #ignore if no repeats res += str(count) res += string[i+1] count = 1 #print last 1 if(count > 1): res += str(count) r...

android - sendBroadcast after asynctask (started in widget onReceive) completes -

goal : update widget view after asynctask completes. scenario : widget onreceive receives intent user click. starts networking operation in asynctask . interface has been passed asynctask via constructor described here . in interface method, i'm trying send broadcast trigger widget's onupdate method don't believe firing. thoughts : best guess onreceive has returned, therefore context trying use sendbroadcast no longer available. thinking get() asynctask don't want trigger anr if operation takes long. if get(timeout, unit) asynctask , i'm afraid risk missing end of task , view not updated. what's best way update widget view upon completion of task? solution : turns out made mistake crafting intent broadcasting if can hold reference of view updated,then invoke view#onupdate in defined interface.if not,and want use broadcast inform view update,so suggest use localbroadcastmanager ,then don't need worry if context exists...

Asp.net MVC 4 Layout -

i new asp.net mvc , programming in general. having issue using layout in asp.net mvc 4. have main layout page. page has jquery , javascript file reference @ bottom above body close tag, , css files in head section below title. have layout, _userlayout, use _layout file. when reference _userlayout file in view, scripts not render. have use script.render on view. why didn't script render when use layout? the regular layout page: @using system.web.optimization; @using microsoft.web.mvc; <!doctype html> <html lang="en"> <head> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <title>@viewbag.title</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link href="~/content/boot...

java - (Noob) Quick help on output statement -

if (gpa < 2.0) system.out.println("the student " +first +last + " not graduating."); this output statement. result the student bobpaul not graduating. how add space between +first , +last way output statement looks like the student bob paul not graduating. the correct answer is system.out.println("the student " +first + " " + last + " not graduating."); it simple. concatenate string " " empty space in between. system.out.println("the student " +first + " " + last + " not graduating.");

GXT re-arrange data array index in TreeStore -

currently, i'm using gxt 3.0.6 i have treestore let's called "treestore", model data "parentdto". private treestore<parentdto> treestore; treestore = new treestore<parentdto>(new modelkeyprovider<parentdto>(){ @override public string getkey(parentdto item){ return string.valueof(item.getparentid()); } }); inside parentdto there list of childdto. if there parentdto data has list of childdto, want show in tree grid. use basic tree grid link https://www.sencha.com/examples/#exampleplace:basictreegrid using reference, if try add 1 parentdto works fine, when problem when add many parent dto. here code adding data treestore public void filltreestore(list<parentdto) listparent){ treestore.clear(); for(parentdto parentdto : listparent){ treestore.add(parentdto); if(parentdto.getlistchild().size() > 0){ for(childdto childdto : paren...

ruby - Spree: Deface getting error NameError in Spree::Home#index -

i'm trying change of front page items listed i'm getting error. using deface correctly change it? telling me <%= link_to small_image(product, itemprop: "image"), url, itemprop: 'url' %> giving me errors, if removed there no pictures. do? update_products.rb deface::override.new(:virtual_path =>"spree/shared/_products", :name => "change site", :replace =>"#products", :text => ' <% paginated_products = @searcher.retrieve_products if params.key?(:keywords) paginated_products ||= products %> <% content_for :head %> <% if paginated_products.respond_to?(:num_pages) %> <%= rel_next_prev_link_tags paginated_products %> <% end %> <% end %> <div data-hook="products_search_results_heading"> <% if products.empty? %> <div data-hook="products_search_results_heading_...

objective c - iOS 9 Error write .plist -

my app errors after update ios 9. can't write .plist file in project. -(bool)writedictionarytoplist:(nsdictionary*)plistdict { nsstring *path = [[nsbundle mainbundle] pathforresource:@"history" oftype:@"plist"]; nsmutabledictionary *dict = [[nsmutabledictionary alloc] init]; [dict setvaluesforkeyswithdictionary:plistdict]; nsdictionary *savedict = [nsdictionary dictionarywithdictionary:dict]; bool result = [savedict writetofile:path atomically:yes]; return result; } result no . but ios 7 , ios 8 works fine. how can fix ? use dictionarywithcontentsoffile: write dictionary plist nsstring *path = [[nsbundle mainbundle] pathforresource:@"history" oftype:@"plist"]; nsmutabledictionary *dict = [nsmutabledictionary dictionarywithcontentsoffile:path]; bool result = [dict writetofile:path atomically:yes]; note since plist app resource cant write file, hence create plist file in documents directory ...

java - I am having trouble calling code from a class -

so new java , working on graphical user interface simple game of minesweeper. had code integrated 1 class , instantiated panel , frame in same class, professor insisted place frame , panel in separate classes. stuck on how implement panel in frame. attempted creating instance of class in main method, when ran program displayed empty frame. before set separate classes code ran panel not being added frame. missing in panel? here code far: import java.awt.event.inputevent; import java.awt.*; import java.util.random; import javax.swing.*; public class minesweeper { public static void main(string[] args) { frame frame = new frame(); frame.getcontentpane().add(new panel()); frame.setvisible(true); } } this frame. class frame extends jframe { public frame() { settitle("minesweeper"); setextendedstate(jframe.maximized_both); setlocationrelativeto(...

java - Understand xmlns , xmlns:somePreFix , targetNamespace in the XSD -

i tried understand these 3 attributes in xsd definition. not sure if right . please correct me .if wrong. thanks compared java class definition xsd definition. the targetnamespace package definition of java class. indicating members including fields , properties , class belong targetnamespace . and need import class members other class consuming them. xmlns , xmlns:someprefix work for. , xmlns default one. yes, targetnamespace tells scope elements of xsd reside in. similar package not same tags inside xml file reside in targetnamespace. on other hand, in java instance variables/methods not belong package directly, belong class. xmlns:someprefix provides convenient "someprefix" alias imported xml schema's namespace. xmlns not not import members of targetnamepace have separate xsd:import tag. rather, referring namespace. can of course use in conjunction xsd:import have "java import like" effect.

c++ - Build fails on secure browser 7 (Firefox 29) -

i came across project https://bitbucket.org/sbacoss/securebrowser7_release , interested in trying build project. so followed guide in readme.md file. i running windows 8.1 , installed vs2010 express edition. have windows driver kit windows 8.1 , have windows sdk 8.1. note:- have vs 2013 express web , vs 2013 express desktop installed other projects work on. now problem after following steps, build fails in first few minutes. below content of log: this file contains messages produced compilers while running configure, aid debugging if configure makes mistake. configure:1197: checking host system type configure:1218: checking target system type configure:1236: checking build system type configure:1311: checking mawk configure:1311: checking gawk configure:1397: checking python2.7 configure:1397: checking python configure:1507: checking python environment mozilla virtualenv configure:1728: checking perl5 configure:1728: checking perl configure:3117: checking gcc configur...

html5 - how to fix ,Backspace is acting as page back in Chrome -

in dynamic web application backspace acting page in chrome , wanted block or @ least warn user leaving page, in case unintentional. please me. its possible duplicate of how can prevent backspace key navigating back? // prevent backspace key navigating back. $(document).unbind('keydown').bind('keydown', function (event) { var doprevent = false; if (event.keycode === 8) { var d = event.srcelement || event.target; if ((d.tagname.touppercase() === 'input' && ( d.type.touppercase() === 'text' || d.type.touppercase() === 'password' || d.type.touppercase() === 'file' || d.type.touppercase() === 'search' || d.type.touppercase() === 'email' || d.type.touppercase() === 'number' || d.type.touppercase() === 'date' ) ) ||...

java - Display HTML text in SWT Label -

i display html text in java swt label. below code creating label. label thelabel = new label(controls,swt.wrap); thelabel.setsize(100,500); thelable.settext("<html><ol><li>hello</li><li>welcome</li></ol></html>"); when run application eclipse application output as: <html><ol><li>hello</li><li>welcome</li></ol></html> what mistake? why not getting html formatted output in label? using eclipse plugin view. to show html swt have use browser widget instead. browser browser = new browser( parent, swt.none ); browser.settext( "<html><ol><li>hello</li><li>welcome</li></ol></html>" ); if don't mind dependency on org.eclipse.ui.forms can use formtext . aware control understand subset of html ( <p> , <b> , <li> , <img> , <br> , <span> ) render simple formatted text. ...

typescript - Any reason to put implements interface to class? -

i'm new type script, browsing tutorial , trying coding in playground found strange. for example code: class foobar implements ifoobar { full: string; constructor (public foo, public bar) { this.full = foo + bar; } } interface ifoobar { foo: string; bar: string; } function test(ifoobar: ifoobar) { return ifoobar.foo + ifoobar.bar; } var obj = new foobar("hello", "world"); document.body.innerhtml = test(obj); works if put class foobar implements ifoobar or just class foobar so what's point of using interface if contract not enforced? update main concern on line: document.body.innerhtml = test(obj); this should throw error right since foobar doesn't use implements ifoobar, , test(ifoobar: ifoobar) specified in method argument should accept ifoobar. me feels typescript plainly think foobar implements ifoobar though isn't. typescript uses duck typing , means if members match, type...

methods - Is Java "pass-by-reference" or "pass-by-value"? -

i thought java pass-by-reference ; i've seen couple of blog posts (for example, this blog ) claim it's not. don't think understand distinction they're making. what explanation? java pass-by-value . unfortunately, decided call location of object "reference". when pass value of object, passing reference it. confusing beginners. it goes this: public static void main( string[] args ) { dog adog = new dog("max"); // pass object foo foo(adog); // adog variable still pointing "max" dog when foo(...) returns adog.getname().equals("max"); // true, java passes value adog.getname().equals("fifi"); // false } public static void foo(dog d) { d.getname().equals("max"); // true // change d inside of foo() point new dog instance "fifi" d = new dog("fifi"); d.getname().equals("fifi"); // true } in example adog.getname() still retur...

javascript - how can load html page in a dialogue and open as popup -

i have separate html page want open dialogue in click of button, possible? how can this? <div id="dialog-form" title="change password"> <form> <div class="border"> <label for="oldpassword">old password</label> <input type="password" id ="oldpassword" placeholder="enter old password"> <label for="newpassword">new password</label> <input type="password" id="newpassword" placeholder="enter new password"> <label for="retypepassword">retype password</label> <input type="password" id="retypepassword" placeholder="enter retype password"> </div> <div class="buttons"> <button id="submit">submit</button> <butto...

php - radio checked lowest value in blade -

the following laravel blade code. want automatically check radio lowest value. { @foreach($service_stages $ss) <input class="" id="money" name="money" type="radio" id="" value="{{$ss->money}}" onclick="generatedate()" checked>{{$ss->money}} @endforeach } first write code find smallest value (e.g. in controller). save variable provide blade view. lets assume have in variable $smallestvalue can try following: @foreach($service_stages $ss) {{ form::radio('money', $ss->money, ($ss->money == $smallestvalue) ? true : false , ['id' => 'money', 'onclick' => 'generatedate()']) }} @endforeach this set checked="checked" if $ss->money == $smallestvalue .