Posts

Showing posts from July, 2011

model view controller - Debugging javascript after pulling the method in via AJAX -

i using mvc , jquery pull in function server (as partial view generate on fly , append body of html) , execute it. works fine, can view in fiddler, debugging terrible. pull in method using like: $("#makegrid").click(function (e) { $.get('/gridder/basicgrid', callbackfn); function callbackfn(data) { //append markup dom $('body').append(data); // call js function partialview here generategrid(); } }); whether best practice or not i'm not sure, if 'view source' after ajax command, code isn't visible, , using debugger; command doesn't seem work. eg: function generategrid() { alert("start"); debugger; alert("end"); } creates 2 alerts doesn't bring debugger though firebug active. discussion raises similar issue. worked around using debugger twice (this bug meant gone now) or opening firebug in ...

ruby - Case insensitive like (ilike) in Datamapper with Postgresql -

we using datamapper in sinatra application , use case insensitive works on both sqlite (locally in development) , postgresql (on heroku in production). we have statements treeitem.all(:name.like =>"%#{term}%",:unique => true,:limit => 20) if term is "berl" suggestion "berlin" both sqlite , postgresql backends. if term is "berl" result sqlite , not postgresql. i guess has fact both dm-postgres-adapter , dm-sqlite-adapter outputting like in resulting sql query. since postgresql has case sensitive like (for unwanted) behavior. is there way case insensitive in datamapper without resorting use raw sql query adapter or patching adapter use ilike instead of like ? i of course use in between, such as: treeitem.all(:conditions => ["name ?","%#{term}%"],:unique => true,:limit => 20) but tied use of postgresql within our own code , not configuration adapter. by writing own data object adap...

Looking for jQuery solution for planning room rentals -

i looking around solution plan occupation of multiple rooms in hotel. normal calendar useless because amount of rooms. thinking of gantt solution, showing rentals in horizontal way , rooms vertically. is there out-of-the-box solution this? thanks jquery ganttview i've used jquery ganttview before , works pretty well. it's light-weight description implies. can used date.js excellent.

How do I count the number of identical characters in a string by position using python? -

for example: string 1: aggcct || | | string 2: agccat these 2 strings identical @ 4 positions, function want return 4. is there clever (i.e., fast) method doing this, other obvious method of iterating through both strings @ same time? thanks! uri i don't think "clever" trick beats obvious approach, if it's executed: sum(c1 == c2 c1, c2 in itertools.izip(s1, s2)) or, if use of booleans arithmetic irks you, sum(1 c1, c2 in itertools.izip(s1, s2) if c1 == c2)

c# - How can I factor out clauses in a parameterized Expression? -

hey all. i'm trying optimize linq entities call statically caching , reusing compiled query. query checks same thing variable number of filter arguments, , way compile query arguments explicitly use number of arguments (rather contains()-type logic, in sql can't parameterized). this works great , gives me major performance boost. problem code ugly. repeat same chunk of code number of times each of possible parameters. i.e: expression<func<entities, string, string, string, string, iqueryable<instrument>>> query = (context, searchterm0, searchterm1, searchterm2, searchterm3) => context.instruments .where( (searchterm0 == null || instr.fullname.indexof(searchterm0) > -1 || instr.shortname.indexof(searchterm0) > -1 || instr.strategies.orderby(st => st.level).select(st => st.name).tak...

cocoa touch - Second UIWindow Not Displaying (iPad) -

i attempting create 2 uiwindows because 2 uinavigationcontrollers on screen @ same time on app. initialize 2 windows in app delegate 1 window's view displayed. know why so? here code used: - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { uiviewcontroller * controller1 = [[uiviewcontroller alloc] init]; [controller1.view setbackgroundcolor:[uicolor graycolor]]; uinavigationcontroller * nav1 = [[uinavigationcontroller alloc] initwithrootviewcontroller:controller1]; [window addsubview:nav1.view]; [window makekeyandvisible]; uiwindow * window2 = [[uiwindow alloc] initwithframe:cgrectmake(0, 0, 100, 100)]; uiviewcontroller * controller2 = [[uiviewcontroller alloc] init]; [controller2.view setbackgroundcolor:[uicolor yellowcolor]]; uinavigationcontroller * nav2 = [[uinavigationcontroller alloc] initwithrootviewcontroller:controller2]; [window2 addsubview:nav2.view]; [wi...

c# - Adding and Retrieving data from request context -

i'm trying attach api key operationcontext outgoing message header follows: public static void addapikeytoheader(string apikey, icontextchannel channel, string address) { using (operationcontextscope scope = new operationcontextscope(channel)) { messageheader header = messageheader.createheader("apikey", address, apikey); operationcontext.current.outgoingmessageheaders.add(header); } } but have no idea how retrieve header on server side. i'm using service authorisation manager , current operating context , try retrieve header this: public string getapikey(operationcontext operationcontext) { var request = operationcontext.requestcontext.requestmessage; var prop = (httprequestmessageproperty)request.properties[httprequestmessageproperty.name]; return prop.headers["apikey"]; } but there no apikey header attached there. also, on debugging when inspect ...

python - How source object can receive feedback information of object at dropping moment (DataSource)? -

i have 1 window - editwindow ( object of class, inherit wx.frame ), contain grid object (self.grid). in class write method: def onsubindexgridcellleftclick( self, event ): .... dragsource = mydropsource( self.grid ) dragsource.setdata( data ) dragsource.dodragdrop() event.skip() and bind in __init__ of editwindow : self.grid.bind( wx.grid.evt_grid_cell_left_click, self.onsubindexgridcellleftclick ) in window - "variablewindow" have got grid - "variablesgrid" , determine following class: class variabledroptarget(wx.textdroptarget): def __init__(self, parent): wx.textdroptarget.__init__(self) self.parentwindow = parent def ondroptext(self, x, y, data): x, y = self.parentwindow.variablesgrid.calcunscrolledposition(x, y) .... in window set drop target: self.variablesgrid.setdroptarget(variabledroptarget(self)) how can hook information of object - "variablesgrid...

vbscript - how to handle IE Download dialog with VB Script? -

how save file automatically in particular location using vb script ? or how possible download file particular location in ie without interacting download dialog ? ultimately need save file in particular location ie automatically. thanks. what file dialogs our selenium tests leverage autoit , free scripting tool creates executables interact windows component object model--including file save dialogs. what make simple script saves file in desired location, compile executable, , in vbscript call program. here script use downloading excel files, although may bit more complicated need. winwait("file download", "", 60) winactivate("file download") if winactive("file download") sleep (500) sendkeepactive ("file download") send("!s") winwait("save as") winactivate("save as") sleep (500) sendkeepactive ("save as") if $cmdline[0] > 0 send($...

"self.included?" in Ruby -

in following code, module test @connection = nil def self.included?(base) @connection = base end def print puts @connection end end class moduletest include test end m = moduletest.new m.print why @connection nil when printing? when run print , prints instance variable @connection of instance of moduletest . have 2 other places in code referring @connection , point instance variable @connection of instance moduletest of class class, , different thing. furthermore, latter @connection (the 1 moduletest class) not value base until included? . the instance variable instance of moduletest created initialized nil default when called puts within print .

web services - How to add new row to a sharepoint list in objective c? -

i tried using updatelistitems web service of sharepoint. not find how give input data in xml format along soap request. thanks in advance since it's integration doing i'd recommend using ado.net adapter sharepoint , connect through wcf service (soap/wsdl). save lot of time , if done correctly integration wont proprietary. check ready-made wcf service, http://www.bendsoft.com/downloads/camelot-wcf-service/ , installation instructions here http://blog.bendsoft.com/category/integrations/wcf-services/ . it's open source ships support camelot xml format, bundles schema along content if query data, check example schema here http://www.bendsoft.com/downloads/sharepoint-web-parts/xml-pusher/ . to insert data sharepoint wcf service can this $sharepointnonquery = new sharepointnonquery(array( 'sql' => "insert contactform (title,email,company,message) values ('john doe','john.doe@example.com','johns company','a tes...

Algorithms Analysis Big O notation -

i need in question. don't understand how it. show, either mathematically or example, if f(n) o(g(n)), a*f(n) o(g(n)), constant > 0. i'll give this. should in right direction: definition of o(n): a function f(n) satisfies f(n) <= c*n arbitrary constant number c , every n above arbitrary constant number n noted f(n) = o(n). this formal definition big-o notation, should simple take , turn solution.

java - not able to transfer Image file -

hi client program transfering image , while transfering image file getting corrupted , not able open image file , i'm not able identify bug , can 1 me. datainputstream input = new datainputstream(s.getinputstream()); dataoutputstream output = new dataoutputstream(s.getoutputstream()); system.out.println("writing......."); fileinputstream fstream = new fileinputstream("blue hills.jpg"); datainputstream in = new datainputstream(fstream); byte[] buffer = new byte[1000]; int bytes = 0; while ((bytes = fstream.read(buffer)) != -1) { output.write(buffer, 0, bytes); } in.close(); i assume s socket , you're attempting transfer file on network? here's example of sending file sockets. sets server socket in thread , connects itself. public static void main(string[] args) throws ioexception { new thread() { public void run() { try { serversocket ss = new serversocket(3434); socket...

javascript - Right-align YUI3 menu bar items? -

i work on project used use yui2 power it's web interface. use menubar plugin, , had couple of menus right aligned. achieved adding float: right css <li> tags surround menu links themselves. worked perfectly. we have upgraded yui3, , no longer works reason, , have no idea why. what correct way right-align 1 or 2 menu items in yui3?

windows phone 7 - WP7 SQL Server CE How to Update -

i'm updating windows phone app mango , starting use sql server ce. can insert , select data struggling understand how update data. most of examples basic tutorials , show inserting , retrieving data not updating. believe need attach class have retrieved data context far have got. please can point me online tutorial showing how this. or example code great. thanks. update basic updating looks simple - query database, update object, call submitchanges. my scenario little more complicated. i have page showing list of jobs. job (jobdetail) selected , page used edit details. job written cache (another table jobcache) while job edited. if user cancels edit cache deleted. if user saves edit jobcache object pulled cache, converted object of type jobdetail , want update database new jobdetail object.i don't think can call submitchanges object not generated query. believe need somehow use attach this. question how? why not original jobdetail object, update chang...

Python - Import file into NamedTuple -

recently had question regarding data types. since then, i've been trying use namedtuples (with more or less success). my problem currently: - how import lines file new tuples, - how import values separated space/tab(/whatever) given part of tuple? like: monday 8:00 10:00 etr_28135 lh1n1522 computer science 1 tuesday 12:00 14:00 etr_28134 lh1n1544 geography ea 1 first line should go tuple[0]. first data: tuple[0].day; second: tuple[0].start; ..and on. , when new line starts (that's 2 tab (\t), start new tuple, tuple[1]). i use separate data: with open(filename) f: line in f: rawdata = line.strip().split('\t') and rest of logic still missing (the filling of tuples). (i know. question, , recent 1 low-level ones. however, hope these others too. if feel it's not real question, simple question, etc etc, vote close. thank understanding.) such database files called comma separated value...

How to handle multipart POST using a URI template of form /prefix/{suffix} in OpenRasta? -

i'm trying handle post of multipart document in openrasta uri template declaration of /content/{contentid}, fails. configuration is resourcespace.has.resourcesoftype<content>().aturi("/content/{contentid}").handledby<contenthandler>().renderedbyaspx("~/views/contentview.aspx").and.asjsondatacontract(); the handler method follows: public operationresult post(string contentid, ienumerable<imultiparthttpentity> entities) {...} i'm using following curl command test ./curl -v -f mypartname=@./hello.txt http://localhost:10247/content/id-1 the post works fine if remove "{contentid}" uri template , modify handler accordingly. any ideas on how resolve? log file follows below. --roland 4-[2011-10-10 02:27:47z] verbose(0) starts pre-executing request. 4-[2011-10-10 02:27:47z] verbose(0) incoming host request http://localhost:10247/content/id-1 4-[2011-10-10 02:27:47z] verbose(0) adding communication context data 4-[2011-1...

How To Create Database Tables in C -

i need code small/simple database application using c, cs degree (so using sqlite or other available application not option. in other words, need re-invent wheel here). my idea use b-tree store items of each table. problem facing tables need flexible hold unknown number of columns, , each column can either string or int. example, command: create table student (string name, int age) i need create table holds string , integer. command instead: create table grade (int grade1, int grade2, int grade3) i need create table holds 3 integers. how can achieve such flexibility? my idea far create struct several unions inside it, each union can either string or int. need put lot of unions inside, sure accommodate columns requested table. example: struct table{ union{ int number; char *text; }column1; union{ int number; char *text; }column2; union{ int number; char *text; }column3; .... }; is there...

c# - Is it possible to bind datatable to the ToolStripMenuItem? -

i'm using contextmenustrip & created submenus under contextmenustrip @ runtime. adding object of toolstripmenuitem class. i'm having 1 datatable table want populate submenus using id & name field datatable further processing of application. is possible? thanks. try this: foreach (datarow dr in datatable.rows) { cms.items.add(new toolstripmenuitem() { text = dr["name"].tostring() }); }

c# - Observer pattern with delegate and events using an event array -

we have class manages many queues store data. want user notified when new data added each of these queues. i'd use observer pattern using delegate , events. single event , source, we'd do: public delegate void newdataaddeddelegate(); public event newdataaddeddelegate newdataadded; and observer: qmanager.newdataadded += new qmanager.newdataaddeddelegate(getnewdatafunc); but in case, have, say, 10 queues, each of can receive data arbitrarily. we'd observer functions subscribe individual queue. thought do: public delegate void newdataaddeddelegate(); public event newdataaddeddelegate [] newdataadded; // can't and in constructor of qmanager: newdataadded = new newdataaddeddelegate[numberofqueues]; and in observer: qmanager.newdataadded[0] += new qmanager.newdataaddeddelegate(getnewdatafunc0); qmanager.newdataadded[1] += new qmanager.newdataaddeddelegate(getnewdatafunc1); but no go, since event expected delegate type, not array of delegates type. a...

javascript - Canvas Isometric game engine - moving the map -

i have been working through tutorial ( http://glacialflame.com/category/tutorial/ ) build isometric game engine, map move character focus point. so, when move - map centres on character. i have little pastebin here: http://pastebin.com/u75pz4yy see in action here: http://www.wikiword.co.uk/release-candidate/canvas/newengine/index.html have fiddle, request! http://jsfiddle.net/neuroflux/vuxyg/2/ note: html5 , canvas browsers only, don't moan if using ie6 ;) any ideas , appreciated, thought updating each of "tiles" in array +1 or -1 respectively, can't seem foreach loop tile images on canvas. cheers in advance! moving map should simple translating context players position. as player moves x or y, should canvas translate same amount (or negative amount) i didnt bother finding right offset make bunny in center of screen, should give idea of how done.

javascript - How to submit a form in an iframe and redirect to a page without frames -

my page contains iframe. inside frame, user can submit form. how can display submitted form in whole window, instead of frame? i've interpreted question as: my page contains iframe. inside frame, user can submit form. how can display submitted form in whole window, instead of frame? answer : set target="_top" in form element: <form target="_top" ...>

java - JSF & Webflow - <h:selectManyListbox> converting troubles -

in jsf, have this: <h:selectmanylistbox id="createaccountbasicinfo_select_types" styleclass="selectmanycheckbox" value="#{party.roles}" size="6" converter="persistenceobjecttostringtwowayconverter"> <f:selectitems value="#{acctypes.selectitems}" /> </h:selectmanylistbox> my converter: //[...] import javax.faces.convert.converter; //[...] public class persistenceobjecttostringjsfconverter implements converter { //[...] public object getasobject(facescontext context, uicomponent component, string value) { long id = long.valueof(value); object object = null; try { object = getpersistenceservice(context).loadbyentityid(id); // here load appropriate record } catch (coreexception e) { e.printstacktrace(); } catch (elementcreationexception e) { e.printstacktrace(); } return object; //here need return arraylist of loaded objects instead of...

iphone - What does the "?" mean in the following statement -

forgive "newbie" question, heck question mark, "?" mean in fololowing line of code? self.navigationitem.leftbarbuttonitem.title = (editing) ? nslocalizedstring(@"done", @"done") : nslocalizedstring(@"edit", @"edit"); this ternary statement, ? conditional operator. statement saying: if (editing) { self.navigationitem.leftbarbuttonitem.title = nslocalizedstring(@"done", @"done"); } else { self.navigationitem.leftbarbuttonitem.title = nslocalizedstring(@"edit", @"edit"); } you think of like: ? - if previous statement true, code after. : - else / otherwise, run code after this. you can read more here http://en.wikipedia.org/wiki/ternary_operation . find construct available in many languages other c / objective-c.

Django/Python - Collect the data to the right form (Algorithm) -

i have models this: item: name desc attrgroup: name order attrname: name group.foreinkey(attrgroup) order attrval: value attr.foreinkey(attrname) item.foreinkey(item) so want compare attributes of n items in list items_id=[1,3,7,...] in views, likes this: attrs = attrval.object.filter(item__id__in=items_id) and send templates. i'm gonna confusing way how arrange list interface. the templates should this: <table> {% g in group %} <tr class="group_name">{{ g.name }}</tr> {% in attrs %} <tr> <td>{{ a.name }}</td> {% in items_id %} <td>{{ value of item 'i' }}</td> { %endfor %} </tr> {% endfor %} {% endfor %} </table> i think have solution issue. thanks! update: follow pretty solution @lott, found out way how show data templates. i'm using co...

javascript - Get Response Header/Body -

i'm developing firefox addon , i'm listening http responses this: var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(httpobserver, "http-on-examine-response", false); which calls httpobserver object looks this: var httpobserver = { observe : function(asubject, atopic, adata) { asubject.queryinterface(components.interfaces.nsihttpchannel); httpstatus = asubject.responsestatus; if(httpstatus == 200 && asubject.contenttype.tostring().indexof("text/") != -1) { alert("url: " + asubject.name + "\r\nstatus: " + httpstatus + "\r\ncontenttype: " + asubject.contenttype); //works great alert("body: " + asubject.responsetext); //is undefined, why? } else if(httpstatus == 404 && asubj...

java - Any simple way to get the queue length of an ActiveMQ? -

how obtain queue length (number of unconsumed messages sent queue) in activemq, using java? you have use jmx, since queue interface not provide such information. example of retrieving size of specific queue: // connection string url = "service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi"; jmxconnector connector = jmxconnectorfactory.connect(new jmxserviceurl(url)); mbeanserverconnection connection = connector.getmbeanserverconnection(); // queue size objectname nameconsumers = new objectname("org.apache.activemq:type=broker,brokername=localhost,destinationtype=queue,destinationname=myqueue"); destinationviewmbean mbview = mbeanserverinvocationhandler.newproxyinstance(connection, nameconsumers, destinationviewmbean.class, true); long queuesize = mbview.getqueuesize(); reference: activemq jmx , required mbeans example: managing activemq jmx apis

encryption - What implementations allow me to detect failed HMAC validations to detect active attacks? -

i'm trying bring awareness around need authentication encryption using software alert , report on failed mac verification attempts, , sharing results middle management. i'm not cryptographer, see value in proper implementation. ideally i'd create report says x attacks prevented. is valid idea, or overly simplistic? if not, should start in implementing it? (low level aes, pgp, etc?) here c# mac code sample modified alert or log when authentication fails. incomplete sample shouldn't used as-is since many other details need considered before implementing authenticate-then-encrypt (ate) or encrypt-then-authenticate (eta) it nice know performance counter, log file, or dll exception relates error. i'll investigating bouncycastle see corresponding exception is. // compares key in source file new key created data portion of file. if keys // compare data has not been tampered with. public static bool verifyfile(byte[] key, string sourcefile)...

jquery - Is there a way to completely remove an HTML element using Javascript? -

is possible remove/delete html element markup directly using javascript/jquery/ajax instead of using css display: none ? yes javascript var parent = document.getelementbyid('parentelementid'); var child = document.getelementbyid('childelementid'); parent.removechild(child); jquery $('#parentelementid').remove('#childelementid');

javascript - Is making POST requests with additional parameters via link_to acceptable? -

it's easy make link in rails make post request. link_to 'click me', some_path, :method => :post . works great... unless need pass additional parameters in. because there's no way make actual post request link, rails fakes request, means if try pass additional parameters some_path , builds query string. when mouseover link looks this: /some_path?foo=var&foo=bar[foo][bar] normally wouldn't bad, except gets ugly if you've got controller expecting nested params. so question is, bother else, or me? the workaround can think of change href # , add hidden form nearby, , add click handler link serializes form , submits when link clicked. makes link degrade ungracefully , awful lot of work amounts aesthetic gripe. i'm pretty obsessive urls. there easier way? or being crazy , should deal params in query string? the web ugly place, , 1 of things that's annoying can't make link post without creating form or doing wild javascript handle...

Waiting for completion of one-way WCF call in a C# console application -

i have wcf webservice (not under control) implements functionality need access via isoneway=true + callback interface, 1 of methods of notifies of processing completion. has been written way designed access gui. however need access same method console application use in batch. crude method of achieving set flag false , after calling wcf method implement while loop brief thread.sleep() call in it. works seems poor way of achieving end result. i'd know proper way of doing is. note: service out of control , reference has been added through ide although can knockup code implementation etc. use manualresetevent waiting completion. call one-way async method on service , wait on manualresetevent object. in callback call set() method let main thread continue execution after waitone() call so: var waithandle = new manualresetevent(); yourwcfobject.calltheonewaymethod(); waithandle.waitone(); void callbackmethodraisedbywcfservice() { waithandle.set(); }

Java String variable setting - reference or value? -

the following java code segment ap computer science practice exam. string s1 = "ab"; string s2 = s1; s1 = s1 + "c"; system.out.println(s1 + " " + s2); the output of code "abc ab" on bluej. however, 1 of possible answer choices "abc abc". answer can either depending on whether java sets string reference primitive types (by value) or objects (by reference). to further illustrate this, let's @ example primitive types: int s1 = 1; int s2 = s1; // copies value, not reference s1 = 42; system.out.println(s1 + " " + s2); // prints "1 42" but, had bankaccount objects hold balances. bankaccount b1 = new bankaccount(500); // 500 initial balance parameter bankaccount b2 = b1; // reference same object b1.setbalance(0); system.out.println(b1.getbalance() + " " + s2.getbalance()); // prints "0 0" i'm not sure case strings. technically objects, compiler seems treat them primitive types...

How to call php function which is inside a class (external file) from jquery? -

in php script @ top have require_once('../registration/include/membersite_config.php'); wich class site functions. class called fgmembersite . there function inside normaly call $fgmembersite->stats have call jquery function. in same php script have jquery code: $('a.slick-toggle').click(function(){ var the_id = $(this).attr('href'); var div_id = $('#job_' + the_id); if ($(div_id).is(":visible")==false) { //here put ajax call } $(div_id).toggle(400); return false; }); i want call stats() function form jquery code when condition trigered, function inside class wich loaded requiere_once top. normaly when make ajax call pass parameters via post function writen in other php file using example: $.ajax({ url: 'addremovelive.php', data: {addname: val,addlevel: val1}, type: 'post',success: function(d) {$('#add_lang_level').val('');$('#add_lang').val(...

web.xml - How do I provide basic http authentication for static tomcat webapps without changing tomcat-users.xml? -

i have access tomcat manager , can upload war-files. 1 of these wars static web project (zipped html + media files, renamed *.war). want add web-inf/web.xml file war protect content basic http auth. i know how adding global users , assigning roles in tomcat-users.xml , want have usernames , passwords defined in war-file. can done without touching tomcat's tomcat-users.xml ? and if yes, how specify in static project's web.xml ? thx, juve i found solution here: http://wiki.metawerx.net/wiki/securingyoursitewithcontainermanagedsecurity the page describes how define own meta-inf/context.xml pointing own web-inf/users.xml . unfortunately, link users.xml file has absolute, , not want make assumptions on os/filesystem paths in config files. here current web-inf/web.xml : <?xml version="1.0" encoding="iso-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/xmlschema...

SML - How to create a list out of a postorder scan of a tree -

how implement function in sml gets tree , returns list. list consists of values in tree nodes according postorder scan of tree. the tree datatype is: datatype 'a tree = leaf | branch of 'a * 'a tree * 'a tree; that can done by: fun createlist(leaf) = [] = | createlist(branch(el, left, right)) = createlist(left) @ createlist(right) @ [el]; if have branch first visit it's left subtree ( createlist(left) ), it's right subtree ( createlist(right) ) , afterwards append element el , postorder tree traversal does. if want create list leaf (an empty tree) result empty list.

objective c - Apply filteredArrayUsingPredicate on specific column of a multidimensional NSMutableArray -

i have multidimensional mutable array contains various objects in each dimension. position 1 = foodid int, position 2 = itemname nsstring ie. row 1 [1, "jif"]; row 2 [2, "skippy"]; row 3 [3, "peter pan"]; when try use following code below throws exception because tries evaluate position 1 string //---get peanut butter types beginning letter--- nspredicate *predicate = [nspredicate predicatewithformat:@"self beginswith[c] %@", alphabet]; nsarray *beginwith = [food filteredarrayusingpredicate:predicate]; exception 'nsinvalidargumentexception', reason: 'can't substring operation isn't string' can on how can filter using predicate specific column of multidimensional array? there various examples of nsdictionary can applied key can't seem apply specific position in array. you trying find or filter array using predicate main datasource ("food") array have...

asset pipeline - Dynamic (S)CSS in rails 3.1 -

i'm trying allow user customize application using yml files. when user updates things css needs updated well. i'd solve problem using dynamic css instead. way planning on doing have settings scss file other css files import , use. here have far: settings.scss.erb: $width: <%= rails.application.config.width %>px; main.css.scss: //= require settings @import "settings"; #main { width: $width; } but error: invalid css after "$width: ": expected expression (e.g. 1px, bold), "<%= rails.appli..."` so seems settings not being passed through erb parser before being handed off scss parser, there way solve this. i'd rather not put in .erb files since text editor doesn't support (syntax highlighting , commands) when having scss in erb files side stepping problem erb not being parsed, not going able customize css dynamically (i think main file may require erb extension). asset pipeline designed serve asse...

ajax - What's the Best Way to Open a TCP Stream to Server? -

rather hard nail down question, i'm wondering best way (and not "what's opinion" "which adequately meet requirement shall set forth) open stream connection client side webpage server such either can send data other without polling? i'm thinking term http binding vs. http polling. context here chat application - i'd streamed connection browser isn't pushing requests out. client end here knockoutjs , jquery. i'd able have data pushed , forth json (or @ least manipulatable jquery , knockout's tojson ). server end - not quite sure going be, i'll running on linux server, compatible works fine. if there's more details can provide, let me know - i'm sure left obvious detail out. also, i'm aware there's duplicate question on this, if answer closing dupe , putting in link, that's great. thanks! i think you're looking referred comet. basic idea keep http requests open longer periods of time server can send da...

python - Listbox updating -

when run displays percent after it's done downloading there way make display downloads it? listbox = listbox(admin) listbox.grid(row=19, column=9) def download0(runums, song): chunks = 10000 dat = '' runum = runums.replace(' ', '%20') url = runum down = urlopen(url) downso = 0 tota = down.info().getheader('content-length').strip() tota = int(tota) while 1: = down.read(chunks) downso += len(a) if not a: break dat += percent = float(downso) / tota percent = round(percent*100, 1) sys.stdout.write(str(percent)) sys.stdout.flush() sys.stdout.write("\b"*4) listbox.insert(end, percent) the tkinter event loop (started mai...

vb.net - how to execute part of the code in an another sub procedure -

suppose have 2 buttons btncheck , btnok. want execute few lines code of btncheck btnok. when click on btnok, btnok's code btncheck's code should executed 1 after other. how can in vb.net private sub btnok_click(byval sender system.object, byval e system.eventargs) handles btnok.click .................................. ..............codes 1............. .................................. .........codes btncheck...... .................................. end sub private sub btncheck_click(byval sender system.object, byval e system.eventargs) handles btncheck.click .................................. ..............codes 2............... .................................. end sub [ can done using goto ? ] in addition making separate procedure has been suggested, can call other sub if want run of code: private sub btnok_click(byval sender system.object, byval e system.eventargs) handles btnok.click '... btncheck_click(sender, e) 'this run btncheck code e...

c++ - How can I set member property as tooltip for QGraphicsItem? -

i set item name tooltip qgraphicsitem default. in program, users can change item name, want show correct tooltip after change name. settooltip() accept const qstring, there way accept dynamic changing member property input? i not want use settooltip(qstring) everytime user change item name, since may include many other member properties tooltip, not name. thank you! sice can updated item name, can add signal gets emitted whenever there change in item name , connect signal slot can used set tooltip updated item name along other member properties set to. hope helps.

inline - Define element-level CSS that applies to pseudo-selector -

possible duplicate: css pseudo-classes inline styles is this... <span style="this:hover{color:blue}">turns blue on hover</span> ...possible? no, it's not. use class or id , separate stylesheet :)

optimization - How can I speed up my Java game's FPS? -

i making java game, , game lags lot when paint out graphics. way painting out graphics make bufferedimage , graphics2d it, whole bunch of: g2d.drawimage(loadedimages.getimage(),x,y,null); after print of images bufferedimage , paint bufferedimage screen. there lot of images paint bufferedimage . there better way speed painting time? not know graphics , graphic cards. should use graphics card? should paint directly screen? should use entirely different drawimage() ? the performance should if you're drawing reasonable amount of images. make sure you're not creating new bufferedimage s every time draw screen. example, might have resources singleton in manage of images load , unload each image once. if want more performance, you'll want use opengl. see lwjgl , libgdx , or jogl . may want consider 2d graphics libraries slick .

scheduling - Task Scheduler in c# -

i schedule threads task scheduler 2.0 problem cannot use task scheduler is registered @ os level not program level. there way use task scheduling api invoke thread creation in program? have @ system.threading.timer . this allows specify delegate invoked @ given time.

asp.net - (OAuthException) (#200) exception while posting to facebook wall using facebook c#sdk -

i working on asp.net mvc3 , using facebook c# sdk post on fb wall . following error while trying post on wall. (oauthexception) (#200) user has not granted application permission automatically publish feed stories please see code used . string appaccesstoken = "accessstoken"; //this token got after creatting app in fb developer. facebookclient fb = new facebookclient(appaccesstoken); dictionary<string, object> parameters = new dictionary<string, object>() { {"description", "testbeskrivning"}, {"link", ""}, {"name", "testtitel" } }; fb.post("myfbid/feed", parameters); that's b...

mysql - Show table name where a value is present -

is possible show name of table in db specific value present. have different tables , want show table names contains specific value in of fields. this return lots of empty result sets, non-empty ones correspond table/column combinations fit search. works text, , detects columns contain value (as opposed full column match.) delimiter | drop procedure if exists `searchalltables`| create procedure `searchalltables` ( in _search varchar(256) ) language sql deterministic sql security definer begin -- declare stuff declare _tablename varchar(64); declare _columnname varchar(64); declare _done tinyint(1) default 0; -- examine every string column in database declare _columncursor cursor select table_name, column_name information_schema.columns table_schema = database() , (data_type '%char%' or data_type 'text'); declare continue handler not found set _done = 1; open...

jena - How to create an ontology in Java? -

i've data triplets want write in sort of basic owl ontology. i've triplets like: delhi part of india or india asian country note i've relations "is-a", "part-of", or "related-to". what's simplest way build ontology? working example or reference example website great help! there lot of different things mixed in question, suggest take bit of time (away keyboard!) think through you're trying achieve here. firstly, geographic ontologies can quite complex, , lot of work has been done in area. obvious starting point geonames ontology , gives names geographic features, including cities dehli , countries india. @ least should re-use names places in application, maximise chances data can joined other available linked-data sources. however, don't want whole of geonames in application (i'm guessing), need clear why need ontology @ all. way approach outside of application: rather worry kind of jena model use, star...

security - Secure Communication in Java - Serialized CipherText-Objects vs. Transport-Layer-Encryption vs. RMI over SSL -

i want implement encrypted communication between 2 java servers, both under control. there 3 architectures have in mind , want input on pros , cons of them. architecture 1: whenever invoke remote method, not pass parameters plain text serialized ciphertext-object. use esapi-library this, actual implementation not matter. what's important ciphertext-object contains arbitrary data encrypted symmetric key including mac authentication. symmetric key available pre-shared secret on both servers. architecture 2: don't care encryption on application level delegate transport layer. vpn-tunnel or sort of server-to-server encryption supported. don't have information available on modern application server @ moment. input on welcome well. architecture 3: using javax.rmi.ssl use rmi on ssl. it feels architecture 1 complicated , pain implement. architecture 2 leaves encryption application server. application developer have no control on configuration these features. that...

dijit.form - How to make a Dojo dijit form programmatically -

im new dojo , im trying make ui, using programmatic way. i if show me example of how make form programmarically using dojo dijit.form.form. i've been looking example can find declarative way of it. a more object oriented solution: define( [ "dojo/_base/declare", "dijit/form/form", "dijit/form/textarea", "dijit/form/button" ], function(declare, form, textarea, button) { return declare( "mypackage.myform", form, { textarea: new textarea({}), submitbutton: new button({ type: "submit", label: "ready!" }), constructor: function(args) { declare.safemixin(this, args); }, onsubmit: function() { alert(this.textarea.get('value')); }, postcreate: function() { this.domnode.appendchild( this.textarea.domnode ); this.domnode.appendchild( this.submitbutton.d...

php - Looping over with arrays by grouping matching values -

i writing module website, gives breakdown of test results, need someout put similar this, test title average mark 85% test title 2 average mark 12% the array getting database looks this, array ( [0] => array ( [result_id] => 11 [test_taken] => 2011-10-04 16:22:59 [mark] => 5 [retaken] => false [tests_test_id] => 4 [test_title] => website development css basics [test_slug] => website-development-css-basics [mark_needed] => 90 [retake] => yes [topic_id] => 402 [topics_topic_id] => 402 ) [1] => array ( [result_id] => 12 [test_taken] => 2011-10-04 16:30:02 [mark] => 50 [retaken] => false [tests_test_id] => 5 [test_title] => test [test_slug] => another-test...

python - Why is my RPC total going up? -

Image
i'm trying optimize code, , got problem don't quite understand. on every page of web app, there list of notifications facebook's new ticker. so, on every request, run code in beggining: notification_query = db.query(ticker, keys_only=true)\ .filter('friends =',self.current_user.key().name()) self._notifications_future = notification_query.run() then, find spot, call middle function is: notification_keys = [future.parent() future in self._notifications_future] self._notifications = db.get_async(notification_keys) finally fetch them @ end: context.update({'notifications': self._notifications.get_result() }) every thing works great except this: if call middle function in end of request's function, this: dumb spot and if call in think optimized spot, this: smart spot as can see api usage doubled making "optimization". going on here? call number 2, first snippet in both cases. call number 12 in dumb spot second snipp...

.net - What is the fastest, case insensitive, way to see if a string contains another string in C#? -

edit 2: confirmed performance problems due static function call stringextensions class. once removed, indexof method indeed fastest way of accomplishing this. what fastest, case insensitive, way see if string contains string in c#? see accepted solution post here @ case insensitive 'contains(string)' have done preliminary benchmarking , seems using method results in orders of magnitude slower calls on larger strings (> 100 characters) whenever test string cannot found. here methods know of: indexof: public static bool contains(this string source, string tocheck, stringcomparison comp) { if (string.isnullorempty(tocheck) || string.isnullorempty(source)) return false; return source.indexof(tocheck, comp) >= 0; } toupper: source.toupper().contains(tocheck.toupper()); regex: bool contains = regex.match("string search", "string", regexoptions.ignorecase).success; so question is, fastest way on average , why so? ...