Posts

Showing posts from February, 2013

telerik - How can I control the width of the X-axis labels on a horizontal bar RadChart? -

Image
what properties control width of x-axis labels on horizontal bar radchart? here's looks now: i need labels on left wider. i actually, needed keep auto layout doing thing, , disable auto wrapping way: var item = new chartaxisitem(); item.appearance.rotationangle = autotextwrap.false

jquery - Using Attributes End With to delete elements -

i have been trying implement attributeendswith selector delete multiple elements ids ending "_vb ("[id$="_vb"]"). unfortiunately code have below doesnt work. can me correct code please? <script type='text/javascript'> $(document).ready(function(){ var elem = document.getelementbyid('div[id$="_vb"]'); elem.parentnode.removechild(elem); return false; }); document.getelementbyid doesn't work that, want jquery function ( $ ) $(document).ready(function(){ $('div[id$="_vb"]').remove(); return false; }); http://api.jquery.com/remove/

python - Flask+Apache and 500 Error -

i using flask , apache build website , site , running. however met strange 500 error: 1 500 error take website down, , site never come online again until restart apache. expect flask+apache can serve next visitor after 500 error, anyway, flask thread local. assuming following occassion: @app.route('/<expectsomeinteger>') def hello_world(expectsomeinteger): anumber = int(expectsomeinteger) ..... obviously code above faulty , should use <int:expectsomeinteger> , stuff. if visitor typed letters in "expectsomeinteger"'s place, flask return 500 error. the disaster apache send 500 error page visitors after that! can restart apache make work again! is normal? i remember when visit php+mysql site, after serious errors, site can serve next visitor normal. thanks @sasha chedygov , site working fine now. the problem installed called "mod-python" following linode's library: https://library.linode.com/web-servers

java - JComboBox getSelectedItem is return correct values but .equals not working -

so have jcombobox, able select each of items within fine. in system.out.print correct values, though when preform .equals on string "create map" not caught if control statement. missing obvious here? mapselectionbox = new jcombobox(); mapselectionbox.seteditable(false); map amapvalues; for(entry<string, map> obj : runinfo.gethashmap().entryset()){ amapvalues = obj.getvalue(); mapselectionbox.additem(obj.getkey()); } object addnewmap = new object(){public string tostring(){ return "create map"; } }; mapselectionbox.additem(addnewmap); mapselectionbox.addactionlistener(new actionlistener(){ public void actionperformed(actionevent e) { if(mapselectionbox.getselecteditem().equals("create map")){ xcoordinatestextfield = new jtextfield(); xcoordinatestextfield.seteditable(true); windowcontainer.add(xcoordinatestextfield, "6, 4, right, de

sql - How to do the Recursive SELECT query in MySQL? -

i got following table: col1 | col2 | col3 -----+------+------- 1 | | 5 5 | d | 3 3 | k | 7 6 | o | 2 2 | 0 | 8 if user searches "1", program @ col1 has "1" value in col3 "5", program continue search "5" in col1 , "3" in col3 , , on. print out: 1 | | 5 5 | d | 3 3 | k | 7 if user search "6", print out: 6 | o | 2 2 | 0 | 8 how build select query that? edit solution mentioned @leftclickben effective. can use stored procedure same. create procedure get_tree(in id int) begin declare child_id int; declare prev_id int; set prev_id = id; set child_id=0; select col3 child_id table1 col1=id ; create temporary table if not exists temp_table (select * table1 1=0); truncate table temp_table; while child_id <> 0 insert temp_table select * table1 col1=prev_id; set prev_id = child_id; set child_id=0; select col3 child_id table1

java - TrueType fonts replaced with FreeType fonts in libgdx? -

it seems truetype font , font generator replaced freetype font generator? case, because found post detailing usage (the accepted answer here: truetype fonts in libgdx ), can't find these jar's anywhere in latest sources (0.98 @ time of writing). thanks. yes. truetype font replaced freetype font. don't understand why not able find it, because in link mentioned above have specified path. anyway, if want find freetype jars download latest nightly. open it, , under extension folder see gdx-freetype folder. open , use gdx-freetype.jar.

morelikethis - Solr more like this don't return score while specify `mlt.count` -

i'm using solr's more analyze similar documents. while specify mlt.count argument , if not 15, score don't show. more arguments mlt=true&mlt.fl=text&mlt.count=12 , while text filed has term vector. , fl argument *,score . queried url: http://localhost:8983/solr/collection1/select?q=id%3a1967956383&wt=json&indent=true&mlt=true&mlt.fl=text&mlt.count=12 . when specify mlt.count=15 , score shows up. , after that, query mlt.count=12 again, shows up, too. my solr version 4.0. does have idea? thanks! this has been documented solr bug solr-5042 , , patch posted against solr version 4.3. i've relocated patch 4.2.1 , seen fixes behavior there. if query /mlt handler directly, instead of using mlt component under /select handler, can work around issue, handler accepts count rows=12 instead of mlt.count=12.

asp.net - Web API Nested Resource in URL -

i creating first asp.net web api. trying follow standard rest urls. api return search result records. url should – ../api/categories/{categoryid}/subcategories/{subcategoryid}/records?searchcriteria i planning use odata searching , basic / digest authentication on iis. problem in nested resources. before return search results, need check whether user has access category , sub category. created visual studio 2012 – mvc4 / web api project start with. in app_start folder, there 2 files believe url , order of resource related. 1.routeconfig.cs routes.maproute( name: "default", url: "{controller}/{action}/{id}", defaults: new { controller = "home", action = "index", id = urlparameter.optional } ); 2.webapiconfig.cs config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional } ); with model, works fine if url ../api/records?searchcriteria not

R summarizing multiple columns with data.table -

i'm trying use data.table speed processing of large data.frame (300k x 60) made of several smaller merged data.frames. i'm new data.table. code far follows library(data.table) = data.table(index=1:5,a=rnorm(5,10),b=rnorm(5,10),z=rnorm(5,10)) b = data.table(index=6:10,a=rnorm(5,10),b=rnorm(5,10),c=rnorm(5,10),d=rnorm(5,10)) dt = merge(a,b,by=intersect(names(a),names(b)),all=t) dt$category = sample(letters[1:3],10,replace=t) and wondered if there more efficient way following summarize data. summ = dt[i=t,j=list(a=sum(a,na.rm=t),b=sum(b,na.rm=t),c=sum(c,na.rm=t), d=sum(d,na.rm=t),z=sum(z,na.rm=t)),by=category] i don't want type 50 column calculations hand , eval(paste(...)) seems clunky somehow. i had @ example below seems bit complicated needs. thanks how summarize data.table across multiple columns you can use simple lapply statement .sd dt[, lapply(.sd, sum, na.rm=true), by=category ] category index b

matrix - Using fprintf to print on several lines in Matlab -

question: write procedure called print7 print integer numbers within range 0:100 divisible 7. ten numbers printed on 1 output line. hence write program invokes procedure. this did file = fopen('print7.dat','r'); x = 1:100 x=[1:100] if mod(x,7) == 0; print7 = [x] end end fprintf('print7 %d\n', print7) now it's output becomes number 98 - understand largest number under 100 divisible 7. want 10xn matrix-like result. what do? what doing stores result in variable , overwrites variable in each iteration. print directly instead this: c=0; x=[1:100] if mod(x,7) == 0 fprintf('%3d',x) c=c+1; if mod(c,10) ==0 fprintf('\n') end end end

java - Handler changing UI causes CalledFromWrongThreadException -

i've created handler can accessed anywhere within activity , written method make easier call handler: private handler textfrombgthread = new handler() { @override public void handlemessage (message msg) { // string msg string outputstring = msg.getdata().getstring("output"); // find textview textview output = (textview)findviewbyid(r.id.consoleoutputview); // display output log.i("textoutput","about display message: " + outputstring); output.settext(output.gettext() + outputstring); log.i("textoutput","message displayed"); } }; private void textoutputwrapper (string outputtext) { message msg = new message(); bundle bndle = new bundle(); bndle.putstring("output", "\n" + outputtext); msg.setdata(bndle); textfrombgthread.handlemessage(msg); } so can called background thread with: textoutputwrapper("attemp

javascript - How to use if statements inside a while loop -

i'm novice @ programming , haven't had luck in finding tutorial useful want do. i creating form have 2 drop down selections , 1 input box produce price depending on 2 selections. for first drop down type of event. second selection of adult, child, or student (each selection has own set id). want produce prices dynamically appear in text box based on user's selections sort of following (i'm still figuring out javascript bear me poor example): while eventid == 2 { if registration == adult; price == 45; } any appreciated. i don't think want loop, think logic looking if statement, in "if registration adult, , event id 2, set price equal 45" so: if(eventid == 2){ if(registration == 'adult') price = 45; if(registration == 'child') price = 35; } depending on want do, there number of combinations of logical structures might employ. switch statement comes mind if have lot of event ids.

python - Difficulty with Twitter API Search -

Image
i'm new python twitter api . have set auth twitter, , tried search works fine. t = twitter.twitter(auth=auth) tt = t.search.tweets(q="stackoverflow",rpp=50) this worked fine , can read output. but if try: for page in range(1,6): tt = t.search.tweets(q="stackoverflow", rpp=100, page=page) this crashes error: details: {"errors":[{"code":44,"message":"page parameter invalid"}]} i looked on twitter page , seems page parameter ok optional parameter: https://dev.twitter.com/docs/api/1/get/search . alternatively, how more search results if rate limited 100 results per request. there work around it? you should use max_id value iterate through results. make first request twitter api , read max_id result , send in next request. from docs : to use max_id correctly, application’s first request timeline endpoint should specify count. when processing , subsequent responses, keep track of lo

php - How do I create per page and per category stylesheets in Wordpress? -

i'm trying create many different skins apply depending on page , category of wordpress site. not sure of 2 things: how use or statement in php call on skin1.css stylesheet if is_page('x') or if is_category('1') . (on note, how specify multiple pages and/or categories in same line? why following code displaying text in header of web site? there must better way write these if else statements. tips? i know mess. bare me , in advance. i'm learning php go , once project complete, i'll sit down , digest language , practices. < ?php if (is_page( 'health' ) ) { ?> <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_url'); ?>/css/skins/health-skin.css" /> < ?php } elseif (is_page( 'beauty' ) ) { ?> <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_url'); ?>/css/skins/beauty-skin.cs

linux - Installing Pycharm in Ubuntu 12.10 -

i trying install pycharm through ubuntu terminal , after unpack tar.gz i'm not sure after that. are there instructions this? first, need make sure have oracle java installed. see here on how that. then, run pycharm executable expanded archive. in bin directory.

iphone - ELCUIApplication timeout issue -

i new ios. i have app in have login. after login user can use application. now have functionality if user have no user intraction 2 mins app navigate login screen. i have used - http://www.icodeblog.com/2011/09/19/timing-out-an-application-due-to-inactivity/ for implementing it. everything working fine expect when user login in app , use apple button app in background , not uses device few minutes , iphone in lock mode. now if user open lock , open app, can see black screen,ui not present on there. but if click on keyboard shown login screen's textview nothing visible. my code of main.m nsautoreleasepool *pool = [[nsautoreleasepool alloc] init]; int retval = uiapplicationmain(argc, argv, @"elcuiapplication", nil); [pool release]; return retval; when ever timer of inactivity fires pop view controller root. thanks help. first check background color. if black, make clear color. i had similar problem , solved way.

android - How can I turn On and Off Accessibility Service programmably? -

manually can done going through settings menu ,but there api android exposes change setting through function call? what want achieve disable talkback when app runs. more precise want disable explore touch feature of talkback. so of these do a)disable accessiblity service or b)disable talkback or c)disable talkback feature explore touch a little late on one, perhaps someone. in main class used intent accessibility service class. had on off switch pass boolean on whether or not wanted access public class mainactivity extends appcompatactivity { switch onoffswitch; intent serviceintent; public void onoff(view view){ if(onoffswitch.ischecked()){ log.i("main switch", "turn on please"); serviceintent.putextra("onoffservice", true); } else{ log.i("main switch", "turn off please"); serviceintent.putextra("onoffservice", false); } this.startser

Convert JPG,GIF,EPS and PDF to PDF with Imagemagick in PHP -

i need convert jpg,gif , eps files pdf , vice versa. imagemagick best tool ? have configure imagemagic ubuntu 11.04 , using cli trying convert images pdf, quality bad. whoud best approch convertion ? thanks in advance :) you want support 2 types of files; raster (jpg/gif) , vectorial (eps). conversion 1 set other never lossless. when converting vectorial raster or vice-versa, 1 crucial parameter -density, sets image size before gets converted. imagemagick right tool vectorial raster, it's matter of getting parameters right. transform raster vectorial, better tools autotrace or potrace , aware these tools cannot perfect conversion.

css - Set default focus tab in jQuery UI tabs -

i use #tabs ul li a:focus in css , working perfectly. now, want first tab automatically focused everytime web opened (so user dont need click first). i have tried selected , active . both of them working, not focused. code example : $( "#tabs" ).tabs({ active: 0 }); the code above activate first tab, not focused yet. thanks :d try this: $('#tabs').tabs("option", "active", 1); or $('#tabs').tabs({active, 1}); read set default tab in jquery ui tabs

python - How to use AND condtion in mongokit when a key has multiple values -

i have key in document named "tag". has structure this: "tag": [ { "schemename": "http:\/\/somesite.com\/categoryscheme2", "name": "test tag2", "value": 1, "slug": "test_tag2" }, { "schemaname": "http:\/\/somesite.com\/categoryscheme3", "name": "test tag3", "value": 1, "slug": "test_tag3" } ], the values of tag can passed ',' separated. how can use values in , condition saying return enrty having tag = test_tag3&test_tag2 itried : conditions['tag.slug'] = { '$and': tags } tags array of tags got : pymongo.errors.operationfailure operationfailure: database error: invalid operator: $and use $in instead of $and : conditions['tag.slug'] = { '$in': tags }

android - How can I drag and drop with multiple activities? -

i used service call create floating window floats on other views/activities. window has own activity , different dialog. now want add drag&drop action window, example if long click imageview in floating window, can drag , drop activity (or base activity). i've been tried use onlongclicklistener trigger drag event, , added ondraglistener catch drop event. here's have far : public class myfloatableactivity extends floatactivity { private imageview mimg; private mydrageventlistener mdraglisten; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_no_title); setcontentview(r.layout.float_activity)); // imageview drag&drop test mimg = (imageview)findviewbyid(r.id.drag_img)); mimg.setonlongclicklistener(new imageview.onlongclicklistener() { @override public boolean onlongclick(view v) { clipdata dragdata = clipdata.newplaintex

javascript - Why does is my onchange event triggered when my page loads instead of when I click my radio button? -

i have following code in javascript. i'd alert happen wnen user checks radio button, instead happens when page loads, , nothing happens when radio button gets checked. why? var myradiobutton = document.getelementbyid("myradiobutton"); myradiobutton.onchange=alert("checked!"); the radio button starts off unchecked. in html looks this: <div class="myradiobutton"><input type="radio" id="myradiobutton" name="radiobuttons" />&nbsp; radio button </div> why on earth javascript think onchange event has occurred when page loads? , why doesn't recognize change when check radio button? in fact, whatever element use "onchange" makes alert pop when page loads, without user interaction @ all. misunderstanding how "onchange" works? what mean is myradiobutton.onchange = function() { alert('checked'); }; what did execute alert -function , assign return v

unity3D + kinect interection -

guys working on project uses unity engien , kinect input source ..now according knowledge there not support between unity , kinect sdk ..i have heard zigfu framework not giving me functionalities need..so options me? im thinking take functionalities zigfu , background application build in .net 4.0 , using kinect official sdk ? can connect kinect via 2 interfaces @ same time? i.e zigfu , kinect sdk ....my background app connect unity via pipes ..is agood option? i've done similar. i'd use unity 3d engine , interactions animate model using kinect (kinect sdk). functionality in kinect sdk not available in zigfu, such hand gripping detection. because kinect sdk suitable wpf application, here solution : build unity unity standalone (pc, mac, linux). create wpf application kinect stuff inside. add windowsformshost inside xaml of wpf application. embed unity standalone wpf using windowsformshost. to communication between wpf , unity, can use raknet. work socket d

swing - I can't go to design mode in NetBeans (jframe) -

i building gui using swing jframe. using netbeans, because has nice interface allows create gui clicking. once saved java file of interface. want use file again , works fine, when add file package inside project. cant go design view anymore, option not available. does know how enable design view? looking @ there no .form file. idea how compile file? you can recreate .form file class. please see here: http://wiki.netbeans.org/faqformgeneratingformfile if move / copy class have copy form file since it's not recreated.

indexing - how to search word from String field in Lucene Index -

how search word lucene index string field ? i have lucene index field title ,containts document titles eg: tv not working,mobile not working i want search particular word title . code below gives me result full content,if change full_contenet title dont results. query qry = null; qry = new queryparser(full_content, new simpleanalyzer()).parse("not"); searcher searcher = null; searcher = new indexsearcher(indexdirectory); hits hits = null; hits = searcher.search(qry); system.out.println(hits.length()); as "not" lucene query syntax operator, may problem.

android - how to change display value of x axis in bar graph-achartengine -

Image
i'm using achartengine library forline graph.instead of timestamp how can show date in x-axis my code is public graphicalview getline(context context, linkedhashmap<string, list<item>> data, string value2, string value3) { list<timeseries> series=new arraylist<timeseries>(); set<string> keys = data.keyset(); for(string key:keys) { timeseries series1 = new timeseries(key); list<item> value=data.get(key); for(item itm:value) { double temp=double.parsedouble(itm.getdataitem(value3)); string temp1=null; if(value2.equals("created_time")) { temp1=itm.getcreated_time(); } else { try { temp1=itm.getmodified_time(); } catch (nu

java - Repainting/Revalidating JPanel wont work -

Image
i unclear on how repaint jpanel in existing code. dont understand how paintcomponent being called. firstly, clear jpanel cannot that. i want able press "next move" button , repaint jpanel given change in grid reading colours from. having trouble changing jpanel @ via calls, revalidate(), removeall(), , repaint() tiles jpanel. i call these , nothing happens existing jpanel below of tetris grid (tiles) (pictured).. in below code have nested class extends jpanel , setup function creates window taking in 2d arraylist grid , constructing original grid. how @ least clear jpanel or better redraw new grid... thinking method: public void redraw(grid g) { removeall(); getcolor(); //gets new grid of tiles repaint(); revalidate(); } inside nested jpanel class, doesnt seem change jpanel @ not clear current drawing. public class boardgraphics { public arraylist<arraylist<color>> colours;

android - The specified child already has a parent -

i don't know happening. code crashing , dont find reason. i've linearlayout container of several webviews. linearlayout variablecontent = (linearlayout) this.findviewbyid(r.id.variablecontent); (int i=0; i<5;i++){ xmlmodule modul = modulsrecuperats.get(i); mywebview webview = new mywebview(this); webview customwebviewcontainer = (webview) this.minflater.inflate(r.layout.customwebview, null); customwebviewcontainer = webview._clientsettings(customwebviewcontainer,progressdialog); customwebviewcontainer.loaddata(modul.getcontent(), "text/html", "utf-8"); variablecontent.addview(customwebviewcontainer); } and code crashes when addview called. error: caused by: java.lang.illegalstateexception: specified child has parent. must call removeview() on child's parent first. i can't find reason. can me out? the problem customwebviewcontainer has parent. view cannot have 2 parents, exception thrown. can ass

c# - LINQ : Dynamic select -

consider have class : public class data { public string field1 { get; set; } public string field2 { get; set; } public string field3 { get; set; } public string field4 { get; set; } public string field5 { get; set; } } how dynamically select specify columns ? : var list = new list<data>(); var result= list.select("field1,field2"); // how ? is solution => dynamic linq ? selected fields not known @ compile time. specified @ runtime you can dynamically creating lambda pass select: func<data,data> createnewstatement( string fields ) { // input parameter "o" var xparameter = expression.parameter( typeof( data ), "o" ); // new statement "new data()" var xnew = expression.new( typeof( data ) ); // create initializers var bindings = fields.split( ',' ).select( o => o.trim() ) .select( o => { // property "field1"

c++ - Thread-safe CreateThread? -

is printhello() function pthreads example thread-safe? find these kind of examples online don't understand how can thread-safe. on other hand, if add mutex around code in printhello() function example not multithreaded threads queue in wait previous thread exit printhello() function. also, moving class not member have statically declared pointers non-static functions not allowed createthread() seems. way of solving this? #include <winbase.h> #include <stdio.h> #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #define num_threads 500 dword printhello(lpvoid ohdlrequest) { long tid; tid = (long)getcurrentthreadid(); /* randomly sleep between 1 , 10 seconds */ int sleeptime = rand() % 10 + 1; sleep(sleeptime); printf("hello world! it's me, thread #%ld!\n", tid); return 0; } int main (int argc, char *argv[]) { /* initialize random seed: */ srand (time(null)); handle thr

performance - Fast way to check if binary image has split in two -

i know how find connected components efficiently. looking best way find if binary image contains single component still contains 1 component. inbetween there losses of 1 or 2 pixels. i have heard of edge-based approches , think might good, can't find them on internet except inferior other approaches in labeling connected components. if know related this, please post link.

Is there any method that support calling Modelica operator from Java -

is there method support calling modelica operator java ? if want use modelica operator der() , pre() , on, call them java . is there technology can use? there several ways simulate modelica models java program. directly simulate modelica code, use java interface of existing modelica simulator: openmodelica's java interface java interface dymola another option export modelica code functional mockup unit (fmu) via functional mockup interface (fmi), e.g. using dymola. use java fmi library (e.g. jfmi ) interact fmu. note you'll need supply solver code yourself. far easier fmu raw modelica code. also see this question on so more information exchaning information between modelica , java.

java - different textures in android -

i want make more 1 texture on cube easy possible. there should different texture (picture 1 loaded in loadtexture method, android.png) on each side of cube. part of code: public class square2 { private floatbuffer vertexbuffer; // buffer holding vertices private floatbuffer vertexbuffer2; // buffer holding vertices [and on 6 sides] private float vertices[] = { -1.0f, -1.0f, -1.0f, // v1 - bottom left -1.0f, 1.0f, -1.0f, // v2 - top left 1.0f, -1.0f, -1.0f, // v3 - bottom right 1.0f, 1.0f, 1.0f // v4 - top right }; private float vertices2[] = { 1.0f, -1.0f, -1.0f, // v1 - bottom left 1.0f, 1.0f, -1.0f, // v2 - top left 1.0f, -1.0f, 1.0f, // v3 - bottom right 1.0f, 1.0f, 1.0f // v4 - top right }; [for 6 sides too] private floatbuffer texturebuffer; // buffer holding texture coordinates private floatbuffer texturebuffer2; // buffer holding text

php - connect a class library to application code with a .dll file -

i want connect class library application code .dll file id placed in system on different location , code application code mapping defined in .dll file. php_library -> sessing.dll -> application_code. is possible. there w32api extension allows import functions dlls. worked ok me in past pecl page states : "this package not maintained" there's com/.net extension - in case have com objects. and there's simplified wrapper , interface generator (swig) helps compile existing libraries extensions other languages including php.

Java Android SharedPreferences issues -

i'm making game of tetris on android project school , right im using shared preferences in order save current state of game can resumed on later time , i've come realize when store on 100 or preferences sharedprefernces object starts working in strange way , can save when try call editor clear (e.clear + e.commit) wont remove preferences. i appreciate regarding issue thanks sharedpreferences , lightweight mechanism how persist data. but think game it's not win @ all. sharedpreferences used persisting non-structured data example if have application requires login , when user logged in can save state sharedpreferences , in next activities check whether user logged in or not. in game have (i guess sure) structured data-structures (for instance players , properties (values) reached score, loses, wins etc.). so suggest think mechanism data persisting. try think possibility use classic object serializing or , usage of sqlitedatabase provide more complex

javascript - Prototyping in Java instead of extending -

is javascript-like prototyping anyhow achievable, using reflection? can wrap object inside one, extend functionality 1 or 2 more methods, without wiring original nonprivate methods wrapper class, or extends get? if looking extension methods, try xtend. xtend language compiles java code , eliminates boilerplate code. the following text stolen xtend docs extensions : by adding extension keyword field, local variable or parameter declaration, instance methods become extension methods. imagine want have layer specific functionality on class person. let in servlet-like class , want persist person using persistence mechanism. let assume person implements common interface entity. have following interface interface entitypersistence { public save(entity e); public update(entity e); public delete(entity e); } and if have obtained instance of type (through factory or dependency injection or ever) this: class myservlet { extension entitypersistence ep = factory.g

python - How to check if dictionary has unwanted keys? -

i have 2 lists: keys must in dict keys optional dict how can check if keys must there in dictionary there or not? how can check if of optional keys there in dictionary or not? use dictionary views , sets: missing = set(required) - some_dict.viewkeys() optional_present = some_dict.viewkeys() & optional sets, dictionaries, make membership testing cheap , fast, , set operations make easy test if items present or not. want make required , optional sets starts with. for example, subtraction on sets calculates difference, missing set difference between required list , keys in dictionary. using & operator on sets (normally binary and) gives intersection, optional_present gives keys in dictionary in optional sequence (doesn't have set in case, using set there make sense). for testing individual keys can still use key in some_dict , using set operations avoids excessive looping. note dict.viewkeys() specific python (added in python 2.7)

acl - google storage bucket upload permissions -

i have tried create "vendor dropbox" , using instructions in google cloud storage documntation folloing set of commands executed : creating bucket gsutil mb gs://customer-10 adding external user permissions gsutil chacl -u user@company.com:fc gs://customer-10 adding default acl gsutil chdefacl -u -u user@company.com:fc gs://customer-10 verify acl modifications , using command gsutil getacl gs://customer-10 (verified succesfuly ) <entry> <scope type="userbyemail"> <emailaddress>user@company.com</emailaddress> <name>firstname lastname</name> </scope> <permission>full_control</permission> </entry> but when user accessing bucket , using link https://storage.cloud.google.com/?arg=customer-10&pli=1#customer-10 it not possible upload file bucket . what missing in scenario ? please this issue solved in gsutil version 3.37. wo

animation with video - flash substitute for tablets -

i have project (a website) supposed create interactive animation contain movie , on few graphical elements include text , geometrical shapes. the animation should contain user controls allow user navigate , forth. can in flash, website should accessible tablets , flash not work on those. the idea not know approach should project , hope can find advice here. thank time. if it's simple can try publish android/ios using flash/flash builder(using air). depending on experience javascript , how complex project is, might want try code straight in html using canvas.  createjs toolkit might assets bit. another option using haxe : syntax similar actionscript , can either target native ios/android using nme or html5. haxe/nme has pretty impressive performance compared flash ide when comes compiling.

ios - ShowDefaultAchievementCompletionBanner not showing -

in unity-iphone, i'm using gamecenterplatform.showdefaultachievementcompletionbanner(true) activate gamecenter completion banner. there's no problem if achievement completed 0% 100%, banner shown. if achievement progress updated gradually(e.g. 25% each submission), time achievement completed, doesn't show completion banner. how can make show banner time achievement reaches 100% despite being cumulative? appreciated. thanks!

vim edit - Editing in different position of each line at the same time -

i wonder if there rapid method change this: foo: '' foobarfoo: '' foof: '' fooba: '' foobarbar: '' foooobar: '' to foo: 'foo' foobarfoo: 'foobarfoo' foof: 'foof' fooba: 'fooba' foobarbar: 'foobarbar' foooobar: 'foooobar' obviously, want paste word in line parentheses. ideas? this line works example: %s/\v([^:]*)(:\s*).*/\1\2'\1'/ or love playing macro: qq0ywf'pjq then 99@q (99 how many times want play macro)

gruntjs - Can I have multiple jsHint task configured in a single Grunt file? -

i have grunt file configured 2 different modules. in single task can give multiple sources , works fine. requirement give different options both modules - want different jshint rules both modules , want both projects have separate minified files , common minified file. gruntfile.js -> jshint: { ac:{ options: { laxcomma: true, // maybe should turn on? why have these curly: true, eqeqeq: true, immed: true, latedef: true, onevar: true }, source: { src: ['module1/*.js'] } }, lib:{ options: { laxcomma: true, // maybe should turn on? why have these curly: true, eqeqeq: true, immed: true, latedef: true }, source: { src: ['module2/*.js'] } } } i saw of stack overflow question, find grunt-hub option need create 2 separate files , grunt hub file. dont want that, please guide m

find the Monday or Wednsday before a date in excel -

i have list of assignments in excel 2010. each has due date. assignment must submitted external processing 3 working days before due date. before assignment can sent external processing, must reviewed. submissions review on mondays , wednesday. i want function looks @ date in due date cell , returns date of monday or wednesday (which ever closer) before date 3 workdays before date; x = (3 workdays before due date) submit date = (monday or wednesday before x) i got x thus; =workday.intl(<due date cell>,-3) now need code submit date. if due date monday 3 workdays before previous wednesday can have review on wednesday or need monday before that? if it's latter can use workday , workday.intl assuming due date in a2 =workday.intl(workday(a2,-3),-1,"0101111") if it's former make -3 -2 with approach use workday go 2 or 3 workdays , workday.intl uses "0101111" indicate mon , wed working days , subtracts further day on basis

jquery - Identifying child window closure, close property changing -

i'm trying detect when child window closed. user opens pop , closes pop up. want know when pop closed. seems common solution problem put timer on window question has been answered in multiple places on stackoverflow , elsewhere on web. my problem changing close property on child window , not user closing window. causing this? here code (by way, know , should double ampersand, reason not letting me post them there): var childwindow = window.open(desturl, "thepopup", ""); var count = 1; var polltimer = window.setinterval(function () { alert(childwindow.closed.tostring() + count.tostring()); if (childwindow && childwindow.closed && count > 5) { window.clearinterval(polltimer); handler(); } count++; }, 200); this not working put alert in there try see going on. alerts display following messages: false1 true2 true3 true4 true5 so somewhere between 1 , 2 value of clo

php REGEX help replace text inside of specific symbols -

i have string 1 being [my_name] , being <my_name> i need use regex search text within [ ] , < > brackets , replace bob i provide sample code don't know begin. appreciated so far iv tried this $regex = [\^[*\]] thinking inside [] tags i imagine following should work: preg_replace('/([\[<])[^\]>]+([\]>])/', "$1bob$2", $str); explanation of regex: ([\[<]) -> first capturing group. here describe starting characters using character class contains [ , < (the [ escaped \[) [^\]>]+ -> stuff comes between [ , ] or < , >. character class says want character other ] or >. ] escaped \]. ([\]>]) -> second capturing group. we describe ending characters using character class. similar first capturing group. the replacement pattern uses backreferences refer capturing groups. $1 stands first capturing-group can contain either [ or < . second capturi

c# - Linq Sum inline -

is possible linke this? entity (with 3 properties) ---> int a ---> int b ---> int c from record in dbset select new entity { = record.a b = record.b c = * b } when using object initialization syntax , can assign properties field available @ construction time. so, have 2 options if want c computed off of a , b . can read properties off of record : from record in dbset select new entity { = record.a b = record.b c = record.a * record.b } more complicated situations might make untenable repeat definitions of a , b in way. example, repeating long definition how properties computed might computationally expensive. harder read when similar code repeated. in cases might want have intermediary select class gathers relevant information before final select: from record in dbset select new { = somecomplicatedfunction(record.a), b = somecomplicatedfunction(record.b) } info select new entity { = info.a, b = info.

requirejs - AngularJs and global namespace -

i'm working on project requires embed our angularjs application other websites. application uses requirejs load angularjs. however, current angularjs attach angular object window , can potentially cause conflict other websites using own version of angularjs. wonder if there's away can manually place these angular object specific namespace without breaking code. you may try renaming following in source: http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js /** @name angular */ angular = window.angular || (window.angular = {}), to custom: /** @name angular */ angular = window.angularx || (window.angularx = {}), and use renamed version in code: angularx .

ember.js - EmberJS not displaying results from DS.RestAdapter -

i'm new emberjs , can't seem figure out wrong code. i've read , compared different example projects hoping find "missing link" i'd appreciate second set of eyes on this: i using: handlebars.js 1.0.0-rc.3 ember-latest.js (on aws) ember-data-latest.js (on aws) bleeding edge because keep getting errors whatever on website. index.html : <script type="text/x-handlebars" data-template-name="application"> {{outlet}} </script> <script type="text/x-handlebars" data-template-name="items"> <h2>total entries: {{length}}</h2> {{#if length}} <ul> {{#each item in controller}} <li>{{item.title}}</li> {{/each}} </ul> {{/if}} </script> app.js : window.app = ember.application.create({ log_transitions: true }); // model app.store = ds.store.extend({ revision: 12, adapter: ds.restadapter.extend({ bulkcommit: false, url:

html - Javascript Hover Issue on an Image -

i'm trying create effect javascript. effect: when click on menu show active image symb1.png . following code: css: <style> li{display:inline;padding:0 10px; z-index:-1;} .red{ background-image:url('symb1.png'); background-repeat:no-repeat;} </style> html in body tag <ul id="menu"> <li><a href="#" class="red" onclick="selected(this)">menu</a></li> <li><a href="#" onclick="selected(this)">menu 1</a></li> <li><a href="#" onclick="selected(this)">menu 2</a></li> </ul> finally javasript code before closing html body tag: <script> function selected(obj){ var lilist = document.getelementbyid('menu'); var alist = lilist.getelementsbytagname('a'); (i=0; i<alist.length; i++ ) { alist[i].classname=

jasper reports - How To EXPRESSION with WHERE " count Orders WHERE customer = Mr. Smith "? -

i beginner in ireport , cant program java hope can give me idea. i've managed make chart displays how all customers have ordered in february, march,... etc. thats how did it: in category expression have: $f{month} in value expression have : $f{count(orders)} but want display how only 1 customer (for example customer a) has ordered in february, march,... etc. i have following values can use: month, orders , customers(here customer names saved) -------//-----------update--------------//----------------------------------- i want display chart represents total orders per month of customer. iam trying display 3 customers (my database has 3) in 1 chart (stacked). for example(see picture above): want display total orders customer (yellow) in february. , want display total orders customer b (blue) in february , same customer c. the customers should displayed stacked (3 in every month) , every customer should have different color plus total orders every custom

Lazily serving Django static content with NGINX -

let's i've got django code rooted in /var/my_app . i've got media_root configured @ /var/my_app/files , , media_url /var/my_app/files @ /files . serving these files through uwsgi (or gunicorn, etc.) works fine. now trying use nginx try_files directive serve them without hitting uwsgi. here's i've got: location /files/* { try_files /var/my_app$uri $uri; } wherein understanding if attempting access $hostname/files/photos/thumbs/file.jpg , above location matches, $uri /files/photos/thumbs/file.jpg , nginx tests /var/my_app/files/photos/thumbs/file.jpg , should return file if exists. instead, when access uri, see request passed through uwsgi in uwsgi log, though file exists @ /var/my_app/files/photos/thumbs/file.jpg . doing wrong? read docs on try_files , misunderstanding something. for reference, here django location block: location / { include uwsgi_params; uwsgi_param uwsgi_setenv database_url=[redacted] uwsgi_p

Using django-extensions' CreationDateTimeField with South -

i've upgraded number of created = django.db.models.datetimefield to created = django_extensions.db.fields.creationdatetimefield however, when run ./manage.py schemamigration app --auto then ./manage.py migrate app i get runtimewarning: datetimefield received naive datetime (2013-05-13 11:09:45.149280) while time zone support active. is there special need tell south django-extensions field? this actual migration code: def forwards(self, orm): # changing field 'advertiser.updated' db.alter_column('advertiser', 'updated', self.gf('django.db.models.fields.datetimefield')()) # changing field 'advertiser.created' db.alter_column('advertiser', 'created', self.gf('django.db.models.fields.datetimefield')()) # adding field 'campaign.created' db.add_column('advertiser_campaign', 'created', self.gf('django.db.models.fields.datetimefie

mysql summation with condition on individual rows -

i have table 3 fields (of relevance question). 1 field numeric, other 2 have text-based content. want sum of numeric field follows: group field a if field b equal x, add if field b equal y, subtract abc, x, 25 abc, x, 15 abc, y, 10 def, x, 20 def, y, 5 the above data return: abc, 30 def, 15 my query, ideally, produce equivalent of following following: select fielda, sum(fieldc) sum1 my_table fieldb = 'x' group fielda select fielda, sum(fieldc) sum2 my_table fieldb = 'y' group fielda result = sum1 - sum2 how can in single query? something should work: select fielda, sum(case when fieldb = 'x' fieldc else -fieldc end) result my_table group fielda

rest - Accessing WeChat Web API -

is there way download of user's messages or contacts using sort of web api? have account receiving lot of messages, , need analyze these messages. pretty painful hand, web api real life saver. if mentioned wechat official account, possible using developer server setting. when normal user send message official account, wechat server post xml package preset url, , may store data database further analysis. more information, kindly url: http://admin.wechat.com/wiki/index.php?title=common_messages if mentioned normal user account, know impossible download/capture incomming message web api.

cocoa - NSOpenGLView toggle to fullscreen from within the view -

i'm trying create method toggle between fullscreen , window. i'm trying within class inherited nsopenglview, essentially following this blogpost . works once, going windowed fullscreen; trying go fails in various ways: window screen doesn't updated, or don't manage switch window fullscreen blanks out. trying go , forth few times anyway (mapped 'f' key), program locks up, , in worst case, have restart computer. i've attached code method below; debugging purposes, i've set full frame rectangle smaller, if things freeze, application never @ full screen. the fullscreen example in apple developer examples suggest using controller, , not go fullscreen within inherited nsopenglview. my questions: should use controller instead, , there switch between windowed , fullscreen (creating separate fullscreen view each time)? or should both methods work? if both methods should work, 1 preferred? if both methods can work, doing wrong in current way of imple