Posts

Showing posts from 2013

c# - Binding in winform like in WPF -

i want bind winform's form's width property text on label label's text gets updated every mouse movement made. achieved updating when element on form clicked not continious updating(like if change text in resize handler). how thing? you can bind width property doing this: label1.databindings.add(new binding("text", this, "width")); the problem there form isn't notifying framework property has changed. easiest best bet meat , potatoes way: protected override void onresize(eventargs e) { base.onresize(e); label1.text = this.width.tostring(); } edit: okay, if want use data binding, here way works (but reaching around head scratch ear): add object data source form , set datasource type "system.windows.forms.form". next, add code: public form2() { initializecomponent(); this.formbindingsource.datasource = this; binding binding = new binding("text", this.formbindingsource, "size"...

c# - Set Copy to Output folder by code -

i developing code generation tool, project files(.csprj) created code. there way mark content file copied output directory? ... var project = new buildengine.project(); project.load(projectfile.fullname, projectloadsettings.ignoremissingimports); var builditem = project.addnewitem("content", filename); ... need builditem.copytooutput=true ... project.save(projectfile.fullname); every ideas welcome. thank you. try builditem.setmetadata("copytooutputdirectory", "always");

performance - Persistence.createEntityManager() painfully slow with Hibernate -

i'm having huge performance issues eclipse rcp application, apparently caused hibernate. more specific, application takes extremely long start (up 2 minutes) - profiling , debugging showed creating hibernate/jpa entitymanagerfactory (which happens @ startup) takes extremely long. i've played around lot settings, such using file database rather in-memory , not using hbm2ddl, without success. has ever experienced problems these? i'm using jdk 1.6.20, hibernate 3.5 , hsqldb 1.8 (in-memory configuration). below persistence.xml: <?xml version="1.0" encoding="utf-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="my_db" transaction-type=...

java - why are struts Action classes not thread safe? -

i can read in many websites struts action classes not thread safe . not able understand why . also read book says "struts action classes cached , reused performance optimization @ cost of having implement action classes in thread-safe manner" how caching action classes , being thread safe related? . how caching action classes , being thread safe related? if cache , re-use instances of class, allowing multiple threads access same instance simultaneously, class inherently not thread-safe*. if place mutable instance or static fields on class, results under concurrency unexpected , problematic. on other hand, if each thread has own instance of class, class inherently thread-safe. struts 1 action classes not thread-safe. should not place mutable fields on class, instead using form bean class form fields passed action. struts 2 action classes thread-safe. new copies instantiated each request , placing instance fields on class core concept in framework. ...

Google Website Optimiser Control Javascript -

could explain javascript makes google's website optimiser control script? specifically: first 2 lines, seem empty functions, , why third function wrapped parentheses () ? as far can tell script writing out new <script> presumably loads a/b testing. function utmx_section(){} function utmx(){} (function() { var k='0634742331',d=document,l=d.location,c=d.cookie; function f(n) { if(c) { var i=c.indexof(n+'='); if (i>-1) { var j=c.indexof(';',i); return escape(c.substring(i+n.length+1,j<0?c.length:j)) } } } var x=f('__utmx'),xx=f('__utmxx'),h=l.hash; d.write('<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com'+'/siteopt.js?v=1&utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime=...

postgresql - SQL UNION Question -

can explain me why sql statement: select 'test1' union select 'test2' union select 'test3' returns: test2 test3 test1 i trying figure out logic behind union keyword in aspect. there way return: test1 test2 test3 without using order by clause? in other words, can control execution order of union statements? if matters, using postgre 9.0 , php language many thanks, brett according postgresql docs union : union appends result of query2 result of query1 ( although there no guarantee order in rows returned ).

ruby on rails - Chrome browser can't find partial -

i use following in controller add tasks project model using ajax. def task_add project = project.find(params[:project]) @task = projecttask.new(:description => params[:description]) project.project_tasks << @task render :partial => 'task' end and ajax call: $('#task-add').click(function(){ var taskdesc = $('#task-description').val(); $.ajax({ type: "post", url: "/project_task_add", data: ({project:<%= @project.id %>, description:taskdesc}), success: function(data){ var data = $('<div/>').append(data); $('#tasks').append($('#new-task', data).html()); } }); }); it works fine in firefox chrome gives following error: failed load resource: server responded status of 500 (internal server error) digging deeper in chrome dev tools find following response: <h1>template missing<...

c# - How to make a ajax filter in jquery? -

i trying make filtering user search last name. right have on keypress of course many ajax requests rather have after few keys or that. i return results table(i have partial view generates table info in it) $(function () { $('#lastname').keypress(function () { $.post('actionmethod', { 'lastname': $(this).val() }, function (response) { $('#results').html(response); }); }); }); any ideas how should this. guess logic similar auto complete , know can set how many keystrokes before query db. i think should use timeouts , delay execution of ajax call. if keypress occurs before execution reset timer... $(function () { var timer; $('#lastname').keypress(function () { var _this = this; // need store variable since called out of context timeout cleartimeout(timer); timer = settimeout(funct...

selected class not working jquery function -

the function below show/hides divs tabs can tab between different divs. in addition uses ben alman's bbq plugin http://benalman.com/projects/jquery-bbq-plugin/ allows use button on browser when tabbing between divs. everything works can't link of clicked tab show 'selected'. when click on tab should add "selected" class link shows selected. $(function () { var tabcontainers = $('div.tabs > div'); tabcontainers.hide().filter(':first').show(); $(window).bind('hashchange', function () { var hash = window.location.hash || '#divcontainer'; tabcontainers.hide(); tabcontainers.filter(hash).show(); $('div.tabs ul.tabnavigation a').removeclass('selected'); $('a[hash=' + hash + ']').addclass('selected'); }); $(window).trigger( "hashchange" ); }); first save anchor in var @ start of function var currenct_anchor = $(this); then $('...

c - Switch: Declared Variable outside switch and use it in it -

the following isn't it's part causing problem: int s,p; scanf("%d",s); switch(s) { case 1: { p=10; break; } case 2: { p=15; break; } } printf("%d",p); the problem p prints random , large number, causing it? so used of advice , know have following code: int s,p=0; scanf("%d",&s); switch(s) { case 1: { p=10; break; } case 2: { p=15; break; } default: { printf("number invalid"); return 0; } } printf("%d",p); now it's going default though enter 1 or 2 ok worked thank all! "int p" declaration assigns p arbitrary value: whatever happened in memory. now, if s doesn't equal 1 or 2, value never changes, , that's see. can is add default: clause switch() , assign p meaningful there declare p "int p = 0;"

In jQuery, what is selected with $('<div />', {text : $this.attr('title')})? -

well, i'm quite new jquery , while browsing documentation found tutorial on jquery site developing plugins. while reading , trying understand, found can't find answer for. example in section 6.3 data has such code in it: var $this = $(this), data = $this.data('tooltip'), tooltip = $('<div />', { text : $this.attr('title') }); i understand declaration of several variables on 1 line, however, last 1 - tooltip - 1 i'm interested in. can patient ignorance , explain me content of tooltip variable after processing line? thank in advance. it creates new div element, , passes value of $this.attr('title') jquery.fn.text more information: http://api.jquery.com/jquery/#jquery2 jquery( html, props ) html: string defining single, standalone, html element (e.g. or ). props: map of attributes, events, , methods call on newly-created element. and as of jquery 1.4, s...

Equivalent of IsFilled="false" for PathFigure in Path Mini-language (Silverlight/WPF) -

Image
i'm trying find equivalent of isfilled="false" used in pathgeometry, path mini . you can see 2 paths below identical, except 1 geometries has isfilled="false" in second <pathgeometry>.<pathgeometry.figures>.<pathfigure> . desired behavior, i'd have path mini (i.e. in first <path> ). i've looked through documentation , can't seem locate on appears path mini not collection of figures. as understand it, shapes/geometries converted path mini @ run-time, there way reflect compiled xaml see how interpreter renders 1 pathgeometry path mini? <canvas background="#fdb" width="800" height="600"> <!-- left-hand path in picture above --> <path canvas.left="100" canvas.top="100" stroke="#385d8a" strokethickness="2" strokelinejoin="round" fill="#4f81bd" data="m0,0l102,0l102,102l0,102z m46.15,49.01l-73.36,...

uiviewcontroller - Reloading same cocos2d scene shows pink screen -

i making game in cocos2d. game scene has menu button take main menu uiviewcontroller. when user chooses play again , same game scene called run in director, pink screen appears on top of game scene. it because of replacing same scene itself. so, replaced empty scene first when main menu called. code replacing scene is: if ([[ccdirector shareddirector] runningscene] == null) { [[ccdirector shareddirector] runwithscene: [myscenelayer scene]]; } else { [[ccdirector shareddirector] replacescene:[myscenelayer scene]]; } it checks, if there no scene running starts game scene first time. if scene running, in case empty scene, replaces game scene. dealloc of game scene called means old scene destroyed properly. then, replacing empty scene game scene gives pink screen while replacing other new scene not give problem. what can reason , solution? finally, problem caught , resolved. needs careful play of adding , removing views. removing openglview superview when comin...

c# - Can't find PInvoke DLL 'cellcore' - problem -

i try motorola sdk radio and got error: can't find pinvoke dll 'cellcore'. what can problem ? i'am using mc3190 thanks in advance you need add extension dllimport: [dllimport("cellcore.dll")] also see http://msdn.microsoft.com/en-us/library/aa446543.aspx

c# - Code contracts, forall and custom enumerable -

i using c# 4.0 , code contracts , have own custom gameroomcollection : ienumerable<gameroom> . i want ensure, no instances of gameroomcollection ever contain null value element. don't seem able this, though. instead of making general rule, have tried plain , simple example. allgamerooms instance of gameroomcollection . private void setuplisteners(gameroom newgameroom) { contract.requires(newgameroom != null); //... } private void setuplisteners(model model) { contract.requires(model != null); contract.requires(model.allgamerooms != null); contract.assume(contract.forall(model.allgamerooms, g => g != null)); foreach (gameroom gameroom in model.allgamerooms) setuplisteners(gameroom);//<= warning: code contracts: requires unproven: newgameroom != null } can see, why haven't proven, gameroom not null ? edit: adding reference object before iterating not work either: ienumerable<igameroom> gamerooms = model.allgameroo...

bind - How to rebind jQuery Color box after some items have been filtered -

a have galeria of items shows bigger picture after clicking. after filtering elements (using .hide() ), colorbox slideshow keeps showing elements. i've tried use: $('.colorbox').die().live('click', function() { $.fn.colorbox({href:$(this).attr('href'), open:true}); return false; } but show slideshow items in rel item clicked. how can rebind items not filtered? have tried removing rel attribute when hiding filtered elements? can in jquery using removeattr

javascript - Disable Autoload (via IE Helpbar Popup) of ActiveX Control -

in ie 9, have activex control loaded using object tag, ie like: <object id="asdf" classid="clsid:..." codebase="asdf.cab##version=1,2,3,4"></object> . unless control has been installed, on page load bar pops asking if want install. there way disable this? i'd load control if it's installed , nothing if not. thanks ps pointers javascript info re activex controls , object tags appreciated, can't seem find via google. remove codebase attribute , display innertext of object tag instead of attempting install control when isn't installed on system.

ruby on rails - nested form triggering a 'Can't mass-assign protected attributes warning -

i've got multi layer nested form user->tasks->prerequisites and in same form user->tasks->location the location form works fine, i'm trying specify prerequisites current task. prerequisite task_id stored in :completed_task field. when submit form, following error in output warning: can't mass-assign protected attributes: prerequisite_attributes one warning each task in user. i've gone through other questions related this, ensuring field name :completed_task being referenced correctly, adding attr_accessible model (it there , extended it). i'm not sure else i'm supposed doing. my models like class task < activerecord::base attr_accessible :user_id, :date, :description, :location_id belongs_to :user has_one :location accepts_nested_attributes_for :location has_many :prerequisites accepts_nested_attributes_for :prerequisites end class prerequisite < activerecord::base attr_acce...

java - How to apply a mask to a String? -

hi have credit card number string. need apply mask hide cc number: i have "123-123-123" , need "123-xxx-123" is there elegant way this? i'm trying avoid using severals substring() functions... thanks in advance myccstr = myccstr.replacefirst("-[0-9]{3}-", "-xxx-");

ruby on rails - Using Paperclip to direct upload files to S3 -

so i've got paperclip set uploadify upload things s3. have made setup stuff gets loaded directly s3 , when it's done post webserver results... all file name , size. supposed build own processor or before_post_process method "download" file s3 in order process it? or missing , uploadify should have provided me stream file inside after done posting s3? how guys go direct uploads s3 , notifying paperclip backed model? have pull files server , post-processing on them or paperclip handle of that? here couple blog posts describing how it... http://www.railstoolkit.com/posts/uploading-files-directly-to-amazon-s3-using-fancyupload http://www.railstoolkit.com/posts/fancyupload-amazon-s3-uploader-with-paperclip they use fancyuploader (which uses mootools/flash) upload directly s3, bypassing heroku , dreaded 30 second request timeout together, , use delayedjob queue post-processing tasks thumbnailing , paperclip actual processing of files. if can work...

c# - Double Buffer a custom control in the Compact Framework -

i have custom control inherits panel . end putting several datagrids , labels on panel. when gets long auto scrolls me. i need scrolling because list of scanned in objects grow larger space on screen allow. but when scroll flickers quite lot. love have give me smooth scrolling. i have seen several "compact framework" double buffer examples out there, double buffering draw methods (ie graphics.drawstring ). custom control not painting itself. puts normal grids , labels on panel , lets panel paint them. is there way double buffer normal controls (again not custom painting)? the compact framework controls not have doublebuffered property or underlying double-buffering mechanism. there's no way add either. the way double-buffering override painting of control , own.

asp.net - making a radio button remain selected on postback -

i using gridview first column template field radio buttons. i need make first radio button in first row of grid remain default selected during page load / postback. how can done? read this: http://www.asp.net/data-access/tutorials/adding-a-gridview-column-of-radio-buttons-vb the heading titled "using literal control inject radio button markup" may of particular interest you

routing - what is the best way to create an asp.net mvc controller action with lots of variables -

i have url http://www.mysite.com/runreport and controller action: [compressfilter] public actionresult runreport(int field1, int field2, int field3, int field4, int field5, int field6, . . .) so run query filter, wind of having this: http://www.mysite.com/runreport/0/0/0/0/0/1/0. . . . is there better way of doing without such ugly url , routing? i want able have persistent url maps specific queries. you don't have have these fields in route. can have them in query string so: runreport?field3=1 you can combine them poco class so public class mymodel { int? field1 { get; set; } int? field2 { get; set; } int? field3 { get; set; } } this makes fields optional , model class can have smarts in too, can determine report want run example. and controller action public actionresult runreport(mymodel model) this work either or post (or whatever other verb want use

iphone - Sending data from my detail view back to my UITableView -

first of all, thank god stack overflow. new @ objective-c/cocoa/iphone development, , site amazing aid. i have window, has tab bar, has navigation controller, loads uitableviewcontroller. clicking "add" button on navigation bar (created programatically), pushes uitableviewcontroller so: invoiceaddviewcontroller *addcontroller = [[invoiceaddviewcontroller alloc] initwithnibname:@"invoiceaddviewcontroller" bundle:[nsbundle mainbundle]]; [self.navigationcontroller pushviewcontroller:addcontroller animated:yes]; this table view controller pushes it's own detail view: uitableviewcell *targetcell = [self.tableview cellforrowatindexpath:indexpath]; generictextfielddetailviewcontroller *dvcontroller = [[generictextfielddetailviewcontroller alloc] initwithnibname:@"generictextfielddetailviewcontroller" bundle:[nsbundle mainbundle]]; dvcontroller.fieldname = targetcell.textlabel.text; dvcontroller.fieldvalue = targetcell.detailtext...

jQuery select and apply style -

i have table lot of td cells. each of cells might have 1 or more divs inside. need take first inner div's inline style , move it parent td's style. how can done in jquery? this simple: $('td div').each(function() { $(this).closest('td').attr('style', $(this).attr('style')); });

c# - How SharePoint Timer Service 'OWSTimer' Works? -

in our application, need build similar sharepoint timer service. service needs installed on web servers in farm. job can scheduled run immidiately, daily, weekly or monthly on or web servers of farm. jobs configuration , schedule stored in database (ms sql 2008). how sharepoint timer service executes these jobs @ scheduled times? does notified sql server? (notification services not available in sql express) does poll sql server after specific intervals find if job needs execution? (does not guarantee precision.) or what? i recommend use existing framework http://quartznet.sourceforge.net/ https://stackoverflow.com/questions/tagged/quartz.net

makefile - How to load a .so file statically with make? -

is there makefile modification can me load shared library(*.so file) statically? you can't link shared library statically (or share static one); they're different animals. can build static library object files, or if that's not possible can convert shared library static 1 tool statifier , link that. a makefile kind of scripting tool; automates tasks hand. must figure out how hand before ask make it.

java - Audio Player in J2ME -

i new j2me. want play audio song in application. have written player p = null; try { p = manager.createplayer(getclass().getresourceasstream("aa.wav"),"audio/x-wav"); p.start(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (mediaexception e) { // todo auto-generated catch block e.printstacktrace(); } where "aa.wav" wav format song placed in resource folder. when debug code getclass().getresourceasstream("aa.wav") it returns null. can please me thanks if resource folder under src then. make it getclass().getresourceasstream("/resource/aa.wav")

.net - TabControl - catch the tab activated event -

i using windows.forms , .net 2.0. in windows tabcontrol; how can catch event fires anytime user switches tab. for example; if have tabcontrol 4 tab pages; call function anytime user switches tab. see here: http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.selected.aspx

c++ - Efficiency of Qt Signals and Slots -

i browsing methods inside of qmainwindow , noticed parts (such resizeevent , winevent) not implemented signals rather have inherit class able override them. my question is, how efficient signals , slots , possible implement these types of functions signals other classes can subscribe to. instance, inside of high performance game engine. from recall, trolltech stated signal/slot call 10 times slower virtual call. should able process tens, if not hundreds of thousands signals per second.

java - Cannot find method symbol -

i don't know if can explain , post proper code make clear, try. have 5 classes. being used check validity of isbn number. getting error "cannot find symbol - method getisbn(). have gui object have instantiated. error comes handler, here: public void actionperformed(actionevent e) { if (e.getsource()==gui.validatebutton) { try { gui.isbntext.getisbn();/////////////error////////// gui.status.settext("isbn " + isbntext.booknum + " valid"); } catch(isbnexception er) { gui.status.settext(er.getmessage()); } } else system.exit(0); i wont post code gui, idea: theres gui, has textfield called isbntext, , in isbntext class, there method retrieve text, called getisbn, code: public isbntext() { super(20); } //retrieve isbn num textfield public string getisbn() throws isbnexception { booknum = ge...

mongodb - Using positional operator with two-level hierarchies in Mongo -

i have hierarchy of, let say, posts -> comments -> votes . how update vote on comment? comment comments.$ , can't comments.$.votes.$ . you cann't right now(there such bug in jira). suppose can update using server side side javascript. check article more details. another way redesign db scheme 1 level deep, example in case of post-> comments-> votes move comments(or votes) in separate collection.

java - Client API + Server Impl -

i have question: how implement correctly in java late/dynamic binding. have situation, when client has api jar (interfaces , abstract classes) , client wants call server/service (via http), these interfaces implemented. how architecturally can done? (i servlet-api/servlet-impl example, , want same...). maybe techniques presented? java uses late binding. or did mean else definition of late binding applies compiled programming languages?

android - multilayer concept -

hello want know whether multilayer concept work in android. if yes means tell me how? you may idea here: layered surfaceviews in framelayout in android and this: http://inphamousdevelopment.wordpress.com/2010/09/22/first-development-blog-post/ both using addcontentview() which add view layers on top of each other. also in frame layout possible have views on top each other layers.

PHP SQL database query error message -

is there wrong sql code? got tutorial, it's returning following error message database query failed: have error in sql syntax; check manual corresponds mysql server version right syntax use near 'limit 1' @ line 1 function get_subject_by_id($subject_id) { global $connection; $query = "select * "; $query .= "from subjects "; $query .= "where id=" . $subject_id ." "; $query .= "limit 1"; $result_set = mysql_query($query, $connection); confirm_query($result_set); // if no rows returned, fetch array return false if ($subject = mysql_fetch_array($result_set)){ return $subject; } else { return null; } } best echo query , see looks like. probably $subject_id contains no value or invalid value. if $subject_id string, should escape (using mysql_real_escape_string) and put inside quotes in query. [edit] you know can put enters in strings too...

android - How can I make a Button more responsive? -

i have noticed buttons don't seem responsive be. applies equally app , other apps i've tried. when press button there tiny bit of lag (edit: estimate 20-50 ms) before button lights in pressed state. apps have managed remove bit of lag, instance realcalc (available in market) buttons switch pressed state after press finger on them. most of time lag not noticeable, in case buttons used in custom number pad, tiny bit of lag disruptive user. realcalc feels more responsive , polished because lag has been removed. my question - how remove lag? aware subclass, override ontouchevent , proceed there, prefer solution using standard controls , options. suspect solution may interfere scrolling, can live that. edit: specifically, lag mentioned time put finger on button , hold there until button switches pressed state. onclick handler called when remove finger again. some answers suggested moving bulk of onclick handler thread. not issue. make doubly sure, have removed click ha...

c# - Better Architecture for .Net Performance : Caching, Serializing or Writing to disk? -

Image
after having hard times performance in winform app, decided redesign separate processing step visual reporting step. picture worth thousand words, drew purpose of question : needless computing/visualisation layers separated, problem first configuration amount of data stored in live memory displayed on flow growing, growing, taking more , more ram space, resulted in computing part squeezed , taking longer , longer (linearly in time) that's why came new design. proved helpful , efficient : processing first, using 100% memory compute, , handling stored results displayed ( a la "generate report" button) so here simple question : options that, , performance-friendly, (caching, serializing, storing in files reading them back, lazy-loading....) thanks in advance edit : data formed of simple , plain line records (actually times series) stored in csv format example with edit, sounds data pretty simple flat records. since volume high, @ file-based stora...

Rails route problem -

class userscontroller < applicationcontroller def edit ... end mu routes.rb match '/user/:id/profile/edit', :to => 'users#edit', :as => "user_profile_edit", :via => "get" my link: <%= link_to image_tag("icons/run.png"), user_profile_edit_path %> exception: no route matches {:controller=>"users", :action=>"edit"} what i'm doing wrong? thanks. you need supply user record. assuming record assigned @user <%= link_to image_tag("icons/run.png"), user_profile_edit_path(@user) %>

java - JSF property transfer from backing bean A to backing bean B -

i'm getting deeper jsf 2.0 @ moment , lacking bit of understanding "transport" of managed bean properties 1 view other. searched bit haven't found example, if point me tutorial or explain things little bit i'd grateful. so here scenario: i'm developing small playground calendar application. first view select.xhtml contains calendar selector, user can pick specific date: <html> ... <h:form> <!-- calendar selector primefaces --> <p:calendar value="#{calendarselect.date}" mode="inline" navigator="true" /> <p:commandbutton value="show entries date" action="day" /> ... my corresponding backing bean looks this: @managedbean(name="calendarselect") @requestscoped public class calendarselectcomponent { private date date = null; ... // getters , setters now when submit form select.xhtml i'm forwarded day.xhtml <html> ... ...

How use ListView in android Tab? -

good day. in app have 3 tab (one activity extend tabactivity , others activitys provides access content). in first tab have imageview, few textview , works. when add listview , in activity contain listview add few rows not show in may tab. can tell me wrong? here code: in startactivity: intent = new intent().setclass(this, goodsandshopsactivity.class); spec = tabhost.newtabspec("shops").setindicator("shops", res.getdrawable(r.drawable.ic_tab_shops)) .setcontent(intent); tabhost.addtab(spec); in goodsandshopsactivity: protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.descriptions); m_shopslayout = (listview) findviewbyid(r.id.shops); m_shoplist = new arraylist<shop>(); m_shopadapter = new shopadapter(m_shoplist, this); m_shopslayout.setchoicemode(listview.choice_mode_single); m_shopslayout.setadapter(m_s...

php - Secure area in Symfony2 -

i have question security features of symfony2. want protect special area of application under /my prefix. my configuration looks follows: security.config: providers: my: entity: { class: myuserbundle:user, property: username } firewalls: public: pattern: /my/login.* security: false my: pattern: /my.* form-login: check_path: /my/login_check login_path: /my/login logout: true access_control: - { path: /my/login.*, roles: is_authenticated_anonymously } when try access login area, works fine, submitting form leads error page, because there no registered controller _security_check route, described in guide : _security_login: pattern: /my/login defaults: { _controller: myuserbundle:auth:login } _security_check: pattern: /my/login_check i think securitybundle hacks process no controller needed. configuration of symf...

python - Tracking Django/FastCGI Process Errors -

i run django based site on nginx fastcgi server. site works great. every 2-3 days, site run unknown problem , stop responding requests. munin graphs shows io blocks read & write per second increases 500% during problem. i wrote python script record the following stats every 1 minute. load averages cpu usage (user, nice, system, idle, iowait) ram usage swap usage number of fastcgi processes ram used fastcgi processes the record shows during problem, number of fastcgi processes doubled (from normal value of 10-15 25-30). , ram usage fastcgi processes doubled (from 17% 35% of total ram on server). memory usage increase required more swap used slow down disk io made server unresponsive. fastcgi parameters used: maxspare=10 minspare=5 maxchildren=25 maxrequests=1000 i guess problem due poorly written python code in part of site. don't know how find out part of code froze existing fastcgi processes , forking new instances. you've limited number of chil...

many to many - How to get Class Model name from ManyToManyField in Django -

i need class model name #django.db.models.fields.related.manytomanyfield object.for example: class source(models.model): groups = models.manytomanyfield(group) def generated_sql(self): print [f.name f in self._meta.many_to_many] #tehere need class model name f, in case be: group thanks in advance groups = models.manytomanyfield(group) def generated_sql(self): print [(f.name, f.related.parent_model) f in self._meta.many_to_many] ipython ftw

C# generics type constraint -

should't valid c# code? class a<t> t : class { public void dowork<k>() k : t { var b = new b<k>(); // <- compile time error } } class b<u> u : class { } the compiler spits error: error cs0452: type 'k' must reference type in order use parameter 'u' in generic type or method 'consoleapplication1.b' shouldn't compiler able figure out k constraint of type t or derived t should reference type (t constrained reference type)? the constraints applied when type parameter specified. type has not been specified k though k being specified u. u requires type reference type, compiler looking confirm k indeed reference type, cannot. therefore, need explicitly state be. the specification states in section 4.4.4: for each clause, type argument corresponds named type parameter checked against each constraint... and later: a compile-time error occurs if 1 or more of type parameter’s co...

iphone - UINavigationBar change Tint color with animation -

is possible change tint animation smoother effect? this doesn't work me: [uiview beginanimations:nil context:nil]; [self.navigationcontroller.navigationbar settintcolor:[uicolor greencolor]]; [uiview commitanimations]; i not sure if possible using native apple components guess using cg generate gradient ... want find out before i'll start building own solution ... cheers guys :) you wouldn't believe length went through make possible; annoyed me no end isn't stock ios feature , transition of tintcolor ugly while animation push/pop viewcontroller smooth. there'a lot of code checks when fade, , i've written class called pspdfnavigationappearancesnapshot preserve navigation state when being popped. (i got idea awesome nimbuskit ) the actual animation pretty easy: [self.navigationcontroller.navigationbar.layer addanimation:pspdffadetransition() forkey:nil]; catransition *pspdffadetransition(void) { return pspdffadetransitionwithdurati...

oop - In VB6 what is the difference between Property Set and Property Let? -

i have created several property set methods, , didn't compile. when changed them property let , fine. i have since studied documentation find difference between property set , property let , must admit being none wiser. there difference, , if offer pointer proper explanation of it? property set objects (e.g., class instances) property let "normal" datatypes (e.g., string, boolean, long, etc.)

asp.net mvc 3 - Late binding issue with MVC3 ViewBag in VB.NET -

i'm trying out mvc scaffolding in vb.net mvc3 project , running issue late binding option strict set on (and want on). this works in c#: public actionresult create() { viewbag.possibleteams = context.teams; return view(); } but virtually same code in vb.net: public function create() actionresult viewbag.possibleteams = context.teams return view() end function causes compiler error option strict on disallows late binding . took @ documentation here: http://msdn.microsoft.com/en-us/library/system.web.mvc.controllerbase.viewbag(vs.98).aspx wasn't helpful. i notice new empty application in c# uses viewbag in homecontroller vb.net version uses viewdata , maybe vb.net limitation. this not trust issue. option strict on disallows late binding. in vb.net, use viewdata object instead , maintain option strict on setting.

.net - Outlook appointment as exchange server level -

i make form can send reminder specific user's exchange outlook account when button clicked on webpage. is possible? ews best approach? i using exchange 6.5, outlook 2003, , .net 3.5. exchange 6.5 exchange 2003. best approach use webdav protocol, not easy. there library available that. might best option.

java - Spring MVC 3 RequestMapping with regular expresssion quantifiers -

the method below fails "patternsyntaxexception: unclosed counted closure near index ... " @requestmapping(value ="/{id:[0-9|a-z]{15}}") public view view(@pathvariable final string id) { ... } looks pattern matcher trimming off the string , losing last }. does know work around bug? i'm having drop qualifier "/{id:[0-9|a-z]+}" - frankly suck! i don't think there workarounds case except manual validation. after all, {name:regexp} syntax introduced solving ambiguities between mappings rather validation. @valid on @pathvariable s solution, it's promised in spring 3.1 ( spr-6380 ). also feel free report bug in spring jira , although don't expect them fix since path variable handling code mess.

java - Utility vs. Composition vs. Inheritance for JAX-RS Response -

i thinking writing utility class creates , returns jax-rs response. goal simplify , standardize generation of response's. here's idea: public object success (class targetclass, string methodname, object responseentity) { uri location = uribuilder.fromresource(targetclass).path(targetclass, methodname).build(localvar1, localvar2); loginfo(location, methodname); //log4j stuff return response.created(location).entity(responseentity).build(); } and there additional methods other response types (e.g. canceled, error, etc). i curious how else may solve design problem, perhaps using inheritance or composition. how have solved in past? did create single utility class well, or did use inheritance or composition design solution? why did go design? this looks low-level utility me. don't on think - creating kind of bespoke response inheritance hierarchy , or new family of composed types (for sake of added 'patterniness') feels unnecessary...

ioc container - AutoFac - Instantiating an unregistered service with known services -

instantiating unregistered service known services (injecting them via ctr). i want avoid container pollution. here way resolve unregistered concrete types container. note autofac constructor finding , selecting logic, registration event handlers remain in force. first, define method: public static object resolveunregistered(this icomponentcontext context, type servicetype, ienumerable<parameter> parameters) { var scope = context.resolve<ilifetimescope>(); using (var innerscope = scope.beginlifetimescope(b => b.registertype(servicetype))) { icomponentregistration reg; innerscope.componentregistry.trygetregistration(new typedservice(servicetype), out reg); return context.resolvecomponent(reg, parameters); } } the idea component registration derived context , resolve in current context. can create handy overloads: public static object resolveunregistered(this icompo...

java - How to convert xml file into mysql? -

i have xml file created mysql database 1 table. <database_name>      <table_name>          <col1>row1</col1>          <col2>row1</col1>      </table_name>      <table_name>          <col1>row2</col1>          <col2>row2</col2>      </table_name> </database_name> need convert xml file mysql database. how can using java? you use xml parsing library dom4j , parse file, loop through results , emit text file contains list of inserts. do know schema or need inferred data? so resultant text file like create table () insert (c1,...cn) values (v1,...vn) then use mysqldump push file db mysqldump -u [username] [databasename] < output.sql ...

iphone - Objective C: store variables accessible in all views -

greetings, i'm trying write first iphone app. have need able access data in views. data stored when user logs in , needs available views thereafter. i'd create static class, when try access static class, application crashes no output on console. is way write data file? or there cleaner solution haven't thought of? many in advance, use singleton class, use them time global data manager classes need accessible anywhere inside application. can create simple 1 this: @interface newsarchivemanager : networkdatamanager { } + (newsarchivemanager *) sharedinstance; @end @implementation newsarchivemanager - (id) init { self = [super init]; if ( self ) { // custom initialization goes here } return self; } + (newsarchivemanager *) sharedinstance { static newsarchivemanager *g_instance = nil; if ( g_instance == nil ) { g_instance = [[self alloc] init]; } return g_instance; } - (void) dealloc { ...

c# - MVC Drop Down List not mapping to Model -

i'm trying develop application in mvc 3 using ef codefirst. when use int properties , convention set foreign key relationships e.g. public class patient { public int consultantid {get;set;} } i setup create , edit page , use html.dropdownlistfor helper produce list of possible consultants @html.dropdownlistfor(model => model.consultantid, ((ienumerable<web.models.consultant>)viewbag.possibleconsultants).select(option => new selectlistitem { text = html.displaytextfor(_ => option.consultantname).tostring(), value = option.consultantid.tostring(), selected = (model != null) && (option.consultantid == model.consultantid) }), "choose...") which works fine, want move having consultant object on patient class e.g. public class patient { public virtual consultant consultant {get;set;} } public class consultant { public virtual icoll...

javascript - navigating a page? -

i'm in page tem.jsp there made call this <a href="submit.htl" target="_parent">image.gif</a> load submit.jsp page on clicking button want go temp.jsp. since opened target attribute can't close javascript window.close() , how can close page? you said "click button go back", why not make "button" link, example of link used them submit.htl ? <a href="temp.jsp" target="_parent">go back</a>

c# - Dynamically loading SQL tables in Entity Framework -

i need dynamically access sql tables using entity framework. here's pseudo code: var account = db.accounts.singleordefault(x => x.id == 12345); which return me account object , contains fields called "prefix", "campaign id" , further information accounts stored in separate sql tables naming convention of prefix_campaignid_main. the tables have same fields thinking of creating new entity isn't mapped anywhere , dynamically loading it, so: var sta01_main = new myaccount(); // "un-mapped" entity db.loadtable('sta01_main').loadinto(sta01_main); i can sta01_main account: sta01_main.accountid . so question is: how access these tables using entity framework? i don't think ef has loadtable , loadinto method, objectontext.executestorequery might you're looking for: http://msdn.microsoft.com/en-us/library/dd487208.aspx this should let execute arbitrary query against database, , map results arbitrary type sp...

c++ - Function parameter - pointer or reference to a pointer? -

void deletechildren(bstnode *node) { // recurse left down tree... if(node->hasleftchild()) deletechildren(node->getleftchild()); // recurse right down tree... if(node->hasrightchild()) deletechildren(node->getrightchild()); // clean data @ node. node->cleardata(); // assume deletes internal data // free memory used node itself. delete node; } // call external code. deletechildren(rootnode); this function deleting bst recursively. i got question first line, bstnode *node , should modify bstnode *& node ? no, pointers passed value, you're in essence "copying" pointer when pass parameter. pass reference when want callee modify parameter in caller.

Improving a fuzzy matching algorithm in Python -

task : take 2 text files , output 100% matches , 75% matches. solution : import difflib import csv # imports , parses files filea = open("h:/comm.names.txt", 'r') try: seta = filea.readlines() finally: filea.close() fileb = open("h:/acad.names.txt", 'r') try: setb = fileb.readlines() finally: fileb.close() # 100% match setmatch100 = set(seta).intersection(setb) match100 = open("h:\match100.txt", 'w') try: item in setmatch100: match100.write(item) finally: match100.close() # remove 100% matches 2 lists seta_leftover = set(seta).difference(setmatch100) setb_leftover = set(setb).difference(setmatch100) #return best match seta_leftover[i] in setb_leftover @ least 75% matching. fmatch75 = open("h:\match75.csv", 'w') match75 = csv.writer(fmatch75) try: match75.writerow(['file a', 'file b']) item in seta_leftover: ...

svn - How do I detect and/or delete empty Subversion directories? -

i have been searching on google couldn't find answer this. how can detect and/or remove empty directories on subversion repository? want delete directories; have in them .svn directory. i running windows , have access svn on command line , have tortoisesvn installed. this you'll have script somehow because there isn't subversion command this. use "svn ls -r url_to_repo_root" , entries end in / not have children in them. "svn ls" directory ends "/" use advantage when scripting this.

javascript - jQuery: DOM Elements: Attributes: query & create -

i have few questions jquery, relating attributes: is there jquery or dom api call use list or clone of attributes of dom element. jquery.attr() api call lets if know name of attribute, if don't, there way? is there jquery or dom api call use create new css rule, besides obvious 1 of dynamically loading new script? it seems possible because when open js debugger in google chrome using ctrl-shift-j, , click on dom element in elements pane, can see of attributes of element without having ask them name. clone whole object, replicate attributes well, http://api.jquery.com/clone/ add new style section head element using append, http://api.jquery.com/append/

sql - Oracle11g numeric overflow in for loop -

i have loop in pl/sql function like: for in min..max loop variables i, min, max declared numeric in case min , max ofen large, range small, ie: min = 3232236033 max = 3232236286 as see range ~256, values oracle throws numeric overflow error , stuck on how working. how should iterate on values? edit ok, have working answer, using of loop of max/min diff, not possible loop through big values in oracle? edit error retrieve is: sql error: ora-01426: nadmiar numeryczny ora-06512: przy "ps.dhcp", linia 88 01426. 00000 - "numeric overflow" *cause: evaluation of value expression causes overflow/underflow. *action: reduce operands. line 88 of code is: for client_ip in min_host..max_host min_host, max_host, client_ip result of inet_aton (numeric representation of ip) it seems problem comes being cast small number (which seems a fault of pl/sql), can change loop type: a while loop works fine set serveroutput on / declare min_...

javascript - Wrapping multiple words with HTML tags using RegExp -

i'm using regexp make quick replacements in potentially large set of text. it's doing providing means syntax highlighting: var text = 'throw new error("foo");'; text = text.replace(/(^|\w)(throw|new|error)(\w|$)/g,'$1<span class="syntax-reserved-word">$2</span>$3'); problem is, highlights "throw" , "error" skips right on "new". regexp specifies beginning of string or non-word, throw or new or error, non-word or end of string. after finds "^throw ", wouldn't search position begin @ n in "new", meaning should match "^new "? try \b (word boundary) instead of non-word-char: text = text.replace(/\b(throw|new|error)\b/g,'<span class="syntax-reserved-word">$1</span>');

sql server 2008 - Use temp table or table variable for stored procedure that returns 100+ rows -

okay creating stored procedure return data our coldfusion power search. i created view, hold data multiple tables, same column names returned of course. then in stored procedure have created simple temporary table this.... create table #tempsearchresults ( search_id int identity, id integer, type varchar(20), title varchar(50), url varchar(250), rank integer ) then added index it, in perhaps limited experience way improve performance. create unique index idx on #tempsearchresults (search_id) then did select massive query insert #tempsearchresults select id, type, title, url, rank + 1200 rank view company_id = @company_id , title @keyword union select id, type, title, url, rank + 1100 rank view company_id = @company_id , title @keyword , description @keyword and goes on having different rank math values found keyword in tables. and @ end does... select id, type, title, url, rank #tempsearchresults group id, type, title, url, rank order...