Posts

Showing posts from March, 2012

java - How to Remove Duplication from Spring 3 MVC Standard and Ajax Request Controllers and Views -

lately i've been running same issue spring mvc applications on , on again, , i'm trying come long term solution. the problem in standard spring 3 controller, add model objects, specify view name (either inline or injected field) , return. problem i've run if have request returns page person, , pets have (not compilable, psuedo): @requestmapping( value="personoverview", method="get" ) public string getpersonoverview(model) { model.add(personrepo.getperson( thename )); model.add(petrepo.getpetsforperson( theperson )); return "personoverviewviewname"; } now, in view able render of information. however, issue arises when updates "pets" person, , want re-render part of page shows pets. not need rewrite rendering logic in jsp fragment or in javascript, need duplicate controller code each portion of getpersonoverview method. if break controller methods smaller chunks, not able render full page, have render each ch...

php - social media feeds - client or server side requests? -

i'm curious other developers when integrating twitter, facebook , other such feed content on site. make these requests , handle on client or server side? seems there number of jquery plugins out there handle type of simple integrations tend have sites, e.g 3 latest posts. previously, using php (twitter became more complicated integrate when switched openauth) content twitter, blogger etc, i'm wondering if there real need when can done javascript. obviously, if javascript isn't enabled feeds wouldn't display. interested hear people in situation! i tend hook directly feeds client-side code, unless i'm doing complicated, need additional validation or cache results of feed. the rationale if grab feeds on server, have 2 download data twice - once api server server, , once server - whereas grabbing directly api in client-side code results in single http request, should arguably load quicker. of course, if you've got lot of traffic, third-party se...

persistence - WF4 Workflow under AppFabric not resuming properly after IISreset -

folks, i've been having trouble wf4 problem. i'm modeling batch engine/work scheduler after ron jacobs' demo in endpoint.tv webcast ( http://archive.msdn.microsoft.com/wf4batchjob ). in example, "work branch" counts inside while loop. sample, send message workflow called sampleengine.xamlx counting. every count, workflow calls parent (jobscheduler.xamlx) , reports progress completed. works , have working - can schedule job , watch progress both in appfabric dashboard , calling queryprogress (a send/receive pair in scheduler workflow). the problem when iireset simulate server failure or other problem, workflows (sampleengine.xamlx , jobscheduler.xamlx) both come online , show "in progress". problem neither of them track more events - seem stalled somewhere. furthermore, neither of them respond service messages in same way see wf services respond when there's no receive activity scheduled workflow's current state. i've added persist a...

c++ - DllMain freezing When register a COM dll -

i try register com dll named mixcenter.dll . have found out dlls dependent on. when executives dllmain first time, freezes , never returns. seems deadlock, don't call loadlibrary , , never execute dllmain . there other reasons situation ? dllmain looks like: bool apientry dllmain(handle hmodule, dword ul_reason_for_call, lpvoid lpreserved) { switch(ul_reason_for_call) { case dll_process_attach: g_hinstdll = hmodule; log(info) <<"--------------begin logging--------------"; return dllentrypoint((hinstance)hmodule, ul_reason_for_call, lpreserved); case dll_thread_attach: break; case dll_thread_detach: break; case dll_process_detach: log(info) << "--------------end logging--------------"; break; } return true; } i log whole execution using dependency walker, essential part ...

C++ how to pass method as a template argument -

suppose have class x : class x { // ... size_t hash() const { return ...; } }; i create std::tr1::unordered_map<x, int, hashfn> want pass in x::hash() hashfn . know can declare own functor object. feel there should way directly passing pointer x::hash() . is there? no; you've shown it, need small utility struct: #include <functional> template<typename t, std::size_t (t::*hashfunc)() const = &t::hash> struct hasher : std::unary_function<t, std::size_t> { std::size_t operator ()(t const& t) const { return (t.*hashfunc)(); } }; then can create unordered_map so: std::tr1::unordered_map<x, int, hasher<x> > m;

asynchronous - c# how to set the code run at final -

i need set line of code run after has finish run. know how that? private void scanbt_click(object sender, eventargs e) { var folder = @"c:\users\shen\desktop\lenzocr\lenzocr\windowsformsapplication1\imagefile"; directoryinfo directoryinfo; fileinfo[] files; directoryinfo = new directoryinfo(folder); files = directoryinfo.getfiles("*.jpg", searchoption.alldirectories); var processimagesdelegate = new processimagesdelegate(processimages2); processimagesdelegate.begininvoke(files, null, null); **//here line of code need run after finish run system.io.file.delete(@"c:\users\shen\desktop\lenzocr\tempfolder\temppic.jpg");** } private void processimages2(fileinfo[] files) { var comparableimages = new list<comparableimage>(); var index = 0x0; foreach (var file in files) ...

php - How do I prevent internet explorer from rewriting my text? -

i have javascript variable contains url, populated outputting script tag php. intention change webpage url under circumstances. var url = "/somepage?q=3&region=1"; the problem url contains sequence "&reg" internet explorer changes "®" without being asked. i've tried escaping whole url htmlspecialchars, breaks other browsers. turning off quirks mode might help, it's not option current system. adding script tag did nothing. edit: figured out 1 solution, "escaping" url concatenation. var url = '<?php implode( "&'+'", explode( '&', '/somepage?q=3&region=1' ) ); ?>'; i realized should mention how change page: document.location.href = url; edit: turns out had error in script tag. minimal example shows same "problem": <script type="text/javascript" /> var url = "/test?mode=preview&region=1"; </script> the...

android - How to add/get the internal application data? -

if have file in /data/data//files/data.dat, how data.dat file ? maked this: file f1 = new file("data/data/carburant.android.com/files/data.dat"); inputstream in = new fileinputstream(f1); i know it's not 100% coorect ? how correct it? , how add file in path? thank much. option #1: call openoutputstream("data.dat"); option #2: call new file(getfilesdir(), "data.dat"); use getfilesdir() option #3: call getfilestreampath("data.dat");

ruby - Getting unique session ID in Sinatra -

i have simple web app built using sinatra, sessions enabled. if understanding correctly, session data stored in encoded cookie. session data changes, value of cookie change also. i need unique session identifier remains constant through entire session. there such identifier. or must create own unique value , store in session myself? thanks! edit: in comment below thought of useful comparison. if had java servlet, use jsessionid unique identifier. need sinatra equivalent jsessionid. from can tell jsessionid used pass session around in query string, , sinatra doesn't have that, @ least not accessible. sinatra uses rack session management, , default uses cookie store session data. there other session options in rack, memcached, unique session id stored in cookie, there rack abstracts away don't ever need see session id (though still accessible, see documentation ). if want go route messing rack middleware in sinatra, if need unique id, easier generate 1 , s...

Is there any JavaScript Grid plugin that have no framework dependency? -

is there javascript grid plugin have no framework dependency? specifically, want able display grid of information sorted , searched per column basis. the best example have found of kind of grid i'd slickgrid. this example of sorting per column feature want. http://mleibman.github.com/slickgrid/examples/example-header-row.html and example of sorting entries per column. click on column's header , entries sorted. http://mleibman.github.com/slickgrid/examples/example4-model.html but slickgrid needs jquery. rather not use jquery, interested in using different javascript framework named spark. http://sparkjs.co.uk/ so looking use simple grid use 2 features. ajax sugar cool too, not extremely important, moment. i needed find js grid component commercial web app. 2 years ago checked several libraries , chose active widgets' grid component. http://www.activewidgets.com/general.intro/ it not have external dependencies. documentation better actual li...

javascript - dynamically load external JS and write response to a div -

i'm embedding delicious feed page. when add script tags inside div loads before rest of js (at bottom of page). i'd load script specified div dynamically after other js has loaded. i've tried getscript function, breaks page when use .html(): $('#delicious').html(function(){ $.getscript("http://feeds.delicious.com/v2/js/bayonnebridge?title=my%20delicious%20bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd"); }); i can't seem wrap head around how can print results of file #delicious div. if want display script in div, shouldn't this, making use of callback function? $.getscript("http://feeds.delicious.com/v2/js/bayonnebridge?title=my%20delicious%20bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd", function(data){ $('#delicious').html(data); }); the result of $.getscript() xmlhttprequest...

jquery - Change web page content if user is on a mobile device -

i have link on website opens iframe in popup box using jquery. jquery script applies function link has specific attribute 'id=calcpop' can see here below. <a href="calculator.html" id="calcpop">click here</a> it works great on computers, buggy on mobile devices. there way detect if user on mobile device , change not have 'id' attribute? if can't use serverside language php, remove id using js – if have jquery, trick: $("#calcpop").attr("id", ""); to detect whether on mobile device involved there lots of mobile devices. you use like: var ismobile = navigator.useragent.match(/mobile/i) != null; to find things mobile in ua (that match ipod/ipad/iphone), not sure others, you'd have check. putting together, in document.ready closure: var ismobile = navigator.useragent.match(/mobile/i) != null; if (ismobile) { $("#calcpop").attr("id", ""); } ...

jquery - div opacity outside in other div -

i looking-for solution opacity. have div (parent) div inside (child). parent div has background image set opacity 0.5. child div smaller parent , in inside see background image opacity 1.0. possible? it not possible. if parent div has opacity set, sub div inherit opacity.

word vba - Adding attachment to mail merge to email -

i trying create mail merge email adds attachment. following procedure outlined in article http://word.mvps.org/faqs/mailmerge/mergewithattachments.html the emails created , sent correct email addresses attachments not being added. have tested , correct file name being used. sub emailmergewithattachments() dim source document, maillist document, tempdoc document dim datarange range dim long, j long dim bstarted boolean dim ooutlookapp outlook.application dim oitem outlook.mailitem dim mysubject string, message string, title string set source = activedocument ' check if outlook running. if not, start outlook on error resume next set ooutlookapp = getobject(, "outlook.application") if err <> 0 set ooutlookapp = createobject("outlook.application") bstarted = true end if ' open catalog mailmerge document dialogs(wddialogfileopen) .show end set maillist = activedocument ' show input box asking user subject inserted email messages m...

How to add an in command to a where clause in LINQ? -

if have clause follows: where item.field == "value" how can change statement in linq be: item.field in ("value1","value2","value3") seems simple, not working. thanks in advance declare "in" values collection in variable first: var collection = new[] { "value1","value2","value3" }; and use in query: ... collection.contains(item.field) ...

sqlite - SQLiteDatabse and ContentProvider in android -

i want create application's own call logs. how use sqlitedatabase or/and contentprovider in application store , retrieve call log information. confused in sqlitedatabese , in contentprovider. please me. confused , stuck here. thanks in advance. appreciated. you need implement sqliteopenhelper , create databases sql storing log. then use instance open(), getwritabledatabase() write to, , remember close() after operations.

c# - Tri-State Checkboxes in WinForms TreeView -

i have treeview allows users select elements of hierarchical data checking or un-checking each item's checkbox. disable box on nodes have children using checkbox hiding technique question , so: ☑ node 1 ☐ node 2 • node 3 ☑ node 3.1 ☑ node 3.2 • node 4 ☐ node 4.1 ☑ node 4.2 but better solution use tri-state check boxes parent nodes, this: ☑ node 1 ☐ node 2 ☑ node 3 ☑ node 3.1 ☑ node 3.2 ☒ node 4 ☐ node 4.1 ☑ node 4.2 since functionality available in win32, question how without drawing boxes myself (e.g., user-drawn control or using image list ). not familiar win32 api @ all; how 1 extend technique linked above enable tri-state checboxes on managed treeview control? have taken @ this ? seems job. might bit dated, (looks article 2004), i'm sure same principles can extended whatever need do.

.net - Can multiple NServiceBus publishers share the same DBSubscriptionStorage? -

looking @ publish-subscribe api , configuration page, seem database schema used nservicebus track subscriptions tracks subscriber endpoint , message type. i had hoped maybe change name of table in order use same database multiple publishers, this thread seems indicate can't . the point - understand , agree notion of having single publisher endpoint per event type - inevitably leads having multiple publishers operating out of same application scope. perhaps operating in different assemblies or processes moot point; regardless, means or publishers share same transactional database. possibility of having create separate sql database every individual publisher seems ridiculous; we'd end hundreds of single-table subscription databases sitting around. does dbsubscriptionstorage track enough information identify publisher well, such multiple publishers can pointed same database? or if not, there configuration change or hack use accomplish same end result? or going ne...

.net - Proper way to put comments in build events command line? -

what's proper way put comments pre/post build event command line? use rem: http://www.robvanderwoude.com/comments.php an example: rem signtool sign /a $(targetpath) xcopy /y "$(targetpath)" "c:\deploy\$(targetfilename)"

scala - Pattern for interruptible loops using actors -

i'm designing actor consumes items endless stream, , need way control when starts , stops using messages. there common pattern implementing interruptible loops actors? thinking of having actor send messages itself. (pseudo scala): class interruptible extends actor { val stream: stream val running: boolean def receive = { case "start" => { running = true consumeitem } case "stop" => { running = false } case "consumenext" => consumeitem } def consumeitem { if (running) { stream.getitem ! "consumenext" } } } is best way go things? thanks! perhaps encoded this: class interruptible extends actor { val stream: stream def inactive: receive = { // behavior when inactive case "start" => self become active } def active: receive = { // behavior when it's active case "stop" => self become i...

asp.net mvc 3 - Cannot receive JSON exception message/content type on remote requests -

i have asp.net mvc3 application, uses json comunicate flash ui. i´m use actionfilterattribute handle json exceptions (from handle json exceptions gracefully in asp.net mvc 2: http://www.dotnetcurry.com/showarticle.aspx?id=496 ): public class handlejsonexceptionattribute : actionfilterattribute { public override void onactionexecuted(actionexecutedcontext filtercontext) { if (filtercontext.exception != null) { filtercontext.httpcontext.response.statuscode = (int)system.net.httpstatuscode.internalservererror; filtercontext.result = new jsonresult() { jsonrequestbehavior = jsonrequestbehavior.allowget, data = new { filtercontext.exception.message, } }; filtercontext.exceptionhandled = true; } } } it´s works ok when executes on localhost, details fiddler: http/1.1 500 internal server error cache-con...

c++ - An integer hashing problem -

i have (c++) std::map<int, myobject*> contains couple of millions of objects of type myobject* . maximum number of objects can have, around 100 millions. key object's id. during process, these objects must somehow marked( 0 or 1 ) fast possible. marking cannot happen on objects (so cannot introduce member variable , use marking process). since know minimum , maximum id (1 100_000_000), first thought occured me, use std::bit_set<100000000> , perform marking there. solves problem , makes easier when marking processes run in parallel, since these use own bit_set mark things, wondering solution be, if had use else instead of 0 - 1 marking, e.g use if had mark objects integer number ? is there form of data structure can deal kind of problem in compact (memory-wise) manner, , fast ? main queries of interest whether object marked, , marked with. thank you. note: std::map<int, myobject*> cannot changed. whatever data structure use, must not deal map itself...

css - Floating big elements next to each other? -

just quick question regarding css positioning. have several "segments" on site 100% wide (fills screen), , want them floated next each other. first 1 visible, other ones off-screen. i've tried playing around positions , overflow property without luck. right pop down below each other instead of floating. this work if elements did not exceed screen width, do, pop down said earlier. i've tried setting huge width "wrapper", 99999px. , setting segments 100%, fill whole 99999px width instead of screen. any ideas? jsfiddle example: http://jsfiddle.net/9xgpb/ do mean this? example fiddle: here i used favourite alternative floats, inline-blocks if take out of fiddle has pretty (gaudy?) colours show allows min-width: 900px; on centered_content div work too, , removed absolute positioning menu content go below it, demo may find useful.. let me know if or if have questions updated jquery , make corrections default word-spacing new exam...

android - How can I embed an SQLite database into an application? -

i think have basic understanding problem maybe someone's able :-) i'm developing android application using eclipse , application make use of database (only reading database implemented). database contains around 4,000 entries i.e. creating , populating database via source code not option. have created database in advance records. but how can "embed" database file application , access it? databse around 500 kb in file size. downloading remote server not option either not allowed. thanks, robert i solved problem by: adding file.db project/assets folder; writing next class: public class linnaeusdatabase extends sqliteopenhelper{ private static string database_name = "dragonfly.db"; public final static string database_path = "/data/data/com.kan.linnaeus/databases/"; private static final int database_version = 1; private sqlitedatabase database; private final context dbcontext; public linnaeusdatabase...

cocoa - Animated GIF in NSImageView -

i'm using nsimageview display animated gif around 80 frames, each frame being 20ms long. nsimageview can display gif animation right 'out of box', problem needs cpu, around 10% continuously (on core i5 proc). instruments shows spends lot of cpu time decoding gif. to make more efficient, have tried following without success: putting frames inside qtmovie , playing (uses 4% process , 15% qtkitserver process plays movie) drawing directly view cgcontextdrawimage (~5% cpu usage) - didn't export gif's frames, created cgimageref 30x30px .png had lying around. i don't know else try. subclassing nsimageview , somehow caching images sounds idea but, alas, i'm beginner in cocoa... ideas appreciated. thanks! check out this article raphael schaad. that's performant gets without super complicated. github repo looks it's ios don't think it'll hard port.

flash - Basic ActionScript 3 sprite tweening -

i'm trying load bitmap stage tween across entirely using code. following works when adds new bitmap image stage leaves last 1 leaving load of same bitmap. any ideas? tried adding "removechild(myloader);" did nothing. many thanks. import flash.display.movieclip; import flash.events.*; stage.framerate = 31; var =0; btn111.addeventlistener(mouseevent.click, go); function go(event:mouseevent):void { this.addeventlistener(event.enter_frame, drawrect); function drawrect(evt:event) { // create new instance of loader class work var myloader:loader=new loader(); // create new urlrequest object specifying location of external image file var myrequest:urlrequest=new urlrequest("logo.png"); // call load method , load external file urlrequest object parameter myloader.load(myrequest); // add loader instance display list using addchild() method addchild(myloader); // position i...

ruby on rails - ActiveRecord relationships and the object model -

hi ran when trying following: posts = user.first.posts posts.find {|p| "p.id" == 123} => activerecord::recordnotfound: couldn't find post without id that trying call activerecord find. it's expecting: posts.find(123) but dont want query db again. need do: posts.to_a.find {|p| "p.id" == 123} i though dealing array, according posts.class. why have call to_a on it? posts.class => array posts.superclass => activerecord::base why can call superclass on posts if it's (presumably) instance of array , why return activerecord::base? also: posts.ancestors.include? activerecord::base => false why false if activerecord::base superclass of posts array? one more. if do: posts.instance_methods(false) it returns instance methods of class of relationship, i.e. post. seems weird since posts array. if create "regular" array: a = [1, 2] a.instance_methods(false) => nomethoderror: undefined method `instance_methods...

Fmincon in matlab running out of memory -

i using matlab's fmincon optimize objective function l2 norm between 2 vectors. there inequality constraint l2 norm between vector optimized , other constance vector. number of parameters size of vector trying minimize in l2 sense. || m*s - s ||_2 s.t. ||s-t||_2 < epsilon m constant matrix, t constant vectors , epsilon constant. so problem me s huge. can have anywhere 400 20000 variables. fmincon runs out of memory when internally trying store matrices. there way solve problem ? thanks ! when run fmincon, should consider adding set of options. @ optimset , : opti = optimset('maxiter',1000) or checkout optimization options . then get_val = fmincon(... , opti) if doesn't work should post code

Find the optimum sequence of keyboard hits to produce the most repeated characters -

you provided 4 possible operations can done on editor (each operation requires one keyboard hit). a ctrl+a ctrl+c ctrl+v now can hit keyboard n times , need find maximum number of a 's can printed. print sequence of keyboard hits. googled answer: http://podlipensky.com/post/2011/02/07/sundays-puzzle.aspx

ms access - How to delete duplicate records in SQL that differ in a single field? -

i'm using access 2007. i have table 20 fields. 1 of fields autonumber id, it's unique. have lot of records in table differ in autonumber id. can't delete ones odd or ids, because pairs of duplicates have both odds or both evens. ideas on how select 1 record each pair deletion? i know done vba, i'm not familiar access vba yet, i'm looking purely sql-based solution. delete * yourtable id not in ( select min(id) yourtable group field2 , filed3 , field4 , etc... <--- other fields, except id )

php - Fetching Results with datetime -

i'm trying fetch results between 2 time intervals. i've done before web app built using y-m-d , having problems y-m-d h:i:s . code below (masked of-course security reasons): $m5b = date('y-m-d h:i:s',mktime(0,0,0,0,0,0,date('y'),date('m'),date('d'),date('h'),date('i')-5,date('s'))); $npm = date('y-m-d h:i:s',mktime(0,0,0,0,0,0,date('y'),date('m'),date('d'),date('h'),date('i')+1,date('s'))); $gm = mysql_query("select * acm lgt !='0000-00-00 00:00:00' , logged between '$m5b' , '$npm'"); i recommend reading on php's strtotime() function , if you're using recent version of php5 datetime object. should clean code no end. with strtotime() $t = strtotime('+5 mins'); $mysqlformatted = date('y-m-d h:i:s', $t); with datetime class $t = new datetime(); $t->modify('+5 mins'); $mysqlformat...

scientific computing - Solving floating-point rounding issues C++ -

i develop scientific application (simulation of chromosomes moving in cell nucleus). chromosomes divided in small fragments rotate around random axis using 4x4 rotation matrices. the problem simulation performs hundreds of billions of rotations, therefore floating-point rounding errors stack , grow exponentially, fragments tend "float away" , detach rest of chromosome time passes. i use double precision c++. soft runs on cpu moment ported cuda, , simulations can last 1 month @ most. i have no idea how somehow renormalize chromosome, because fragments chained (you can see doubly linked-list), think best idea, if possible. do have suggestions ? feel bit lost. thank much, h. edit: added simplified sample code. can assume matrix math classical implementations. // rotate 1000000 times (int = 0; < 1000000; ++i) { // pick random section start int istart = rand() % chromosome->length; // pick end 20 segments further (cyclic) int iend = (ist...

jquery - IE 8 javascript problem -

hi following code throws "object doesn't support property or method" error in ie.. var value = $input.val().replace(/ /g, '').trim(); part of form validation, in every other browser working well, in ie doesnt..please help from ben rowe : add following code add trim functionality string. if(typeof string.prototype.trim !== 'function') { string.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } }

Facebook Connect Registration "Undo" Popup -

i m using facebook registration plugin site registration. when try click register new window opens , shows text quoted below. how block window?? me out. "you've registered {app_name} using facebook account. if didn't mean this, can undo below." thanks!!! you can't block window, it's part of facebook's system, not yours. also, i'm sure if did find way block it, in violation of facebook's api tos.

php - Codeigniter -> Edit Page -

i getting following error when try , access: domain.co.nz/admin/editpage/home/ i following error: php fatal error: call member function getcmspage() on non-object in controllers/home.php on line 22 the issue cannot understand why being passed main “home” controller - main controller. all of models loaded default - http://cl.ly/2u1f3a2b0s2k0i3k3g13 ideal situation what trying load content text area on editing , when submit clicked go same page message saying content updated. admin template <li><?php echo anchor('#','edit pages');?> <?php if(is_array($cms_pages)): ?> <ul> <?php foreach($cms_pages $page): ?> <li><a >permalink?>"><?=$page->name?></a></li> <?php endforeach; ?> </ul> <?php endif; ?> </li...

objective c - Annoying error: Corrupt JPEG data: premature end of data segment -

this last error message before submit app apple (hopefully) , it's driving me crazy. when saving image phone, corrupts file. when tried open file, gives me error corrupt jpeg data: premature end of data segment , crashes. here's code save image: - (void)imagepickercontroller:(uiimagepickercontroller *)picker didfinishpickingimage:(uiimage *)image editinginfo:(nsdictionary *)editinginfo { [picker.parentviewcontroller dismissmodalviewcontrolleranimated:no]; uploadimage = image; int orient = uploadimage.imageorientation; nsstring *theorientation = [nsstring stringwithformat: @"%d", orient]; nsstring *latestidquery = @""; nsarray *results = [database executequery:@"select * processes order id desc limit 0,1"]; (nsdictionary *row in results) { latestidquery = [row valueforkey:@"id"]; } int latestid = [latestidquery intvalue]; int newid = latestid + 1; nsstring *newidstring = [[nsstring alloc] initwithformat:@"%d"...

JQuery: How to attach event to template objects? -

i have template generates images , binding div. <script id="posttemplate" type="text/html"> <div class="post_1"> <div class="postimage"><img src="${imageurl}" alt="image"></div> </div> </script> then bind data <script> $("#posttemplate").tmpl(clientdata).appendto("#imagesarea"); </script> now, want add event handlers created. like ("template img").error(function() {}); adding handlers things click seems work, error fires off before can add handler seems. not sure selector "template img" referencing since dont see template elements. $(function(){ $('template img').live({ click: function() { // on click }, error: function() { // on error } }); }); http://api.jquery.com/live/

python - pythonic way to filter a dictionary of arrays -

i have dictionary looks this: d = { 'a':['a','b','c','d'], 'b':['a','b','c','d'], 'c':['a','b','c','d'], 'd':['a','b','c','d'], } i reduce dictionary new 1 contains 2 keys randomly selected full set of keys, , contains values correspond random keys. here code wrote works, feel there more pythonic way it, suggestions? import random d = { 'a':['a','b','c','d'], 'b':['a','b','c','d'], 'c':['a','b','c','d'], 'd':['a','b','c','d'], } new_d = {} r = d.keys() random.shuffle(r) r = r[:2] r_dict = dict( (k,true) k in r) k in r_dict: = tuple(d[k]) new_a = [] item in a: if item in r_dict: new...

objective c - Pass a struct to a class method -

i wanted able this: vec2 pos(1,5); myactor.position = [coord positionfrom: pos ]; using structure: typedef float32 float; struct vec2 { vec2(float32 xx, float32 yy) { x = xx; y = yy; } float32 x, y; }; coord.h @interface coord : nsobject { } +(cgpoint) positionfrom: (vec2) pos; +(cgpoint) positionfromangle: (float32) angle; coord.mm #import "coord.h" @implementation coord +(cgpoint) positionfrom:(vec2) pos { return cgpointmake( pos.x * 32, pos.y * 32); } +(cgpoint) positionfromangle:(float32) angle { return cgpointmake( cos(angle) * 32, cos(angle) * 32); } @end but these errors (in coord.h, on positionfrom lines): expected ')' before 'vec2' expected ')' before 'float32' this should be: +(cgpoint) positionfrom: (struct vec2) pos; or else have failed import header file defines vec2 . you have trailing ] in return statement of positionfrom: . btw, stylistically, kind of t...

php - google dynamic marker of maps -

what want is: when select on combo box item, items database , show marker have select . doesn't work. here code: index.php <?php session_start(); $_session['sum']=0; include("database/connect_conf.php"); if(!connection()){ echo 'not connect: '.mysql_error(); }else{ connection(); } if(!db_select()){ echo 'not connect dabatase: '.mysql_error(); }else{ db_select(); } $string="select count(province_id) c tbl_cep_forum"; $get_result=mysql_query($string); if($get_result){ $j=1; while($value=mysql_fetch_array($get_result)){ $_session['sum']=$_session['sum']+$value['c']; $j++; } } ?> ...

dom - JavaScript documentation across standardized browsers for Events -

i attempting learn javascript , find task bit difficult in respects. looking event support across major browsers. far events go, there seems 2 general flavors: (1) microsoft way, , (2) standardized way . i aware ie 8 not support dom level 2 events, ie 9 expected support dom level 3 events. on microsoft side there exists distinct list of dhtml events . description of event object available. in standardized way clumping dom level 0 support has no official specification, , dom level 2 events written w3c. standardized way followed of major browsers except msie, namely: firefox, chrome, safari, , opera. each of standardized browsers have varying level of documentation around support of events indicated following links. dom level 0 events gecko dom event handlers safari html reference: supported attributes html, xhtml, , wml in opera presto 2.8 no information chrome. dom level 2 events w3c dom level 2 specification gecko dom events (appears incomplete) other gecko...

scala - Session must be bound error using Squeryl -

update: okay, fixed problem having, i'm still not quite sure doing wrong. in case, wrote following method in ircdb: def tryit[t](p: => t) = { class.forname("org.h2.driver") //what's point in this...? sessionfactory.concretefactory = some(() => session.create(java.sql.drivermanager.getconnection("jdbc:h2:~/irc","scalairc",""), new h2adapter)) transaction { p } } then used so: val query = from(ircdb.channels)(c => select(c)) ircdb.tryit { (r <- query) println("chan: " + r.name) } and works. understanding, believed once session created using sessionfactory, i'd able use transaction { ... } anywhere has proper import. apparently, understanding incorrect. if has add please do. so, started using squeryl project i'm working on might oversight on part. so, first code: i have following imports: import org.squeryl.primitivetypemode._ import java.sql.time...

DB backend webapp testing in java [tool needed] -

i want create test suit java web application. jsp applications jdbc connectivity . requirements follows, 1 - should able test database logic (queries etc) through models. 2 - great if test .jsp pages (if possible) after doing research found dbunit database backend system testing, unfortunately couldnt find resource starter what think testing options have , great if post links resources/ examples well edit: and have come across mock objects (like jmock..), wonder use replacement dbunit ? thanks in advance cheers sameera it's not clear question if want run integration tests (front end + end) or unit tests against database layer. if need tool allows write integration tests, should definitively @ selenium . selenium can generate functional tests navigating web site (jsp pages) , asserting stuff on page exists or it's equal values. selenium comes firefox plugin generate code you. can replay test in browser or export them java code , make them pa...