Posts

Showing posts from February, 2013

scjp - What does redefining static methods mean in Java? -

scjp - What does redefining static methods mean in Java? - i've been reading section on statics in scjp study guide, , mentions next : static methods can't overridden, can redefined what redefining mean? case of having static method exists in both parent , child, same signature, referenced separately class names? such : class parent { static void dosomething(string s){}; } class kid extends parent { static void dosomething(string s){}; } referenced : parent.dosomething(); , child.dosomething(); ? also, same apply static variables, or static methods? it means functions not virtual. example, have object of (runtime) type kid referenced variable of type parent. if invoke dosomething , dosomething method of parent invoked: parent p = new child(); p.dosomething(); //invokes parent.dosomething if methods non-static, dosomething of kid override of parent , child.dosomething have been invoked. the same holds static fields. jav...

Django views thread-safety? -

Django views thread-safety? - i have several view functions process info remote sources. in many cases processing can take on sec complete. simultaneous access these view functions potentially scramble data? in addition, have continually-running background thread populating database. background thread calling of same library functions view functions calling. potential thread-safety issue? if yes, best practices? i'm assuming using python's locking mechanism work, there improve approaches? thanks! -travis for long running processes, utilize celery. for long view, can create model instance, , start celery task populates it. view can show status of instance, self refreshing html until results there. django thread-safety django-views

python - Can't find the cause "TypeError: coercing to Unicode: need string or buffer, NoneType found" -

python - Can't find the cause "TypeError: coercing to Unicode: need string or buffer, NoneType found" - i'm getting error production server: file "/home/example/svn/libs/django/core/handlers/base.py", line 100, in get_response response = callback(request, *callback_args, **callback_kwargs) file "/home/example/svn/src/app/../app/libs/auth/decorators.py", line 125, in __call__ homecoming self.view_func(request, *args, **kwargs) file "/home/example/svn/src/app/../app/membership/decorators.py", line 64, in __call__ homecoming self.view_func(request, *args, **kwargs) file "/home/example/svn/src/app/../app/site/views/system/invoices.py", line 168, in send_via_email_form homecoming sendviaemailformpage(request, pk, what, sending_type).custom() file "/home/example/svn/src/app/../app/security/security.py", line 99, in execute homecoming func(*args, **kw) file "/home/example/svn/src/app...

ruby - How to Locate Target Directory -

ruby - How to Locate Target Directory - does buildr have pre-defined variables, capistrano, directories 'target', 'reports', etc? if not, rather hard-coding location of these directories, how else can locate/determine these paths? the end goal create task on-the-fly create file , insert target directory. buildr defines symbolic names special directories. path_to (aka _ ) method accepts these symbolic names , automatically translates them paths current layout. e.g., define 'foo' puts _(:target, :main, :classes) # => /some/root/foo/target/classes puts path_to(:source, :main, :java) # => /some/root/foo/src/main/java end as antoine noted in reply answer, there's list of these symbolic names in documentation. ruby buildr

java - Unit testing a method that writes serialized objects to a file -

java - Unit testing a method that writes serialized objects to a file - i have static method writes serialized object. how can write junit tests see if works? here method... public static void writetodisk(data data){ try{ fileinputstream fis = new fileinputstream(filename); objectinputstream in = new objectinputstream(fis); datalist = (datalist) in.readobject(); in.close(); } catch(exception e){ datalist = new datalist(); system.out.println("new file created!"); } datalist.insertdata(data); try{ fileoutputstream fos = new fileoutputstream(filename); objectoutputstream out = new objectoutputstream(fos); out.writeobject(datalist); out.close(); } catch(exception e){ e.printstacktrace(); } } } start no file. call meth...

scala - Circumflex initialisation code (or: how to integrate Squeryl) -

scala - Circumflex initialisation code (or: how to integrate Squeryl) - i'm trying utilize squeryl circumflex. squeryl requires initialisation, i'm bit left in dark on , how should set initialisation code. is there place can register startup methods or something? scala sbt

SQL Server group by status query problem -

SQL Server group by status query problem - table temp id status 1 completed 2 approved 3 paid 4 cancel 5 approved 6 paid i want display above recored per bellow table without using union.because client requirement, please provide help this. table temp id status 1 completed 2 approved 5 approved 3 paid 6 paid 4 cancel almost identical dan's answer, sql server (or standards sql database system): select id, status temp order case status when 'completed' 1 when 'approved' 2 when 'paid' 3 when 'cancel' 4 end other concerns - 1) title of question appears misleading, since it's not grouping @ all, and, 2) think have misconception union - there's no guarantee of order in results homecoming union or union all - in union case, there's likely sort operation help server eliminate duplicates, sort performed exclusively server , shouldn't re...

regex - C# - Problem removing items in List1 & List2 from List3 -

regex - C# - Problem removing items in List1 & List2 from List3 - i have file reading in, splitting different lists , outputting them richtextbox read 3 different listboxes. doing of this, have come across not know how fix/work around. my code below , seem having problem understanding why fails work when gets match tworegex = regex.match(...) section of code. code: private void sortdatalines() { seek { // reads lines in file format. var filereader = file.opentext(opengcfile.filename); // creates list lines stored in. var placementuserdefinedlist = new list<string>(); // reads first line , nil it. filereader.readline(); // adds each line in file list. while (true) { var line = filereader.readline(); if (line == null) break; placementuserdefinedlist.add(line); ...

Eclipse Java Search of Mercurial Project -

Eclipse Java Search of Mercurial Project - i'm using mercurialeclipse develop java project stored in mercurial (at google code). have java projects stored in cvs open in same eclipse. eclipse search file search text works projects. search java search references java type fails mercurial project, works other projects. i suspect problem arises because src/ directory in mercurial project 1 layer deeper eclipse expects. is, looks mercurial_project/another_directory/src. if indeed problem, how can configure eclipse adjust it? (it not possible alter construction of mercurial project @ central repository. many other people using it.) thanks arthur versions: eclipse sdk: version: 3.6.1; build id: m20100909-0800 mercurialeclipse 1.8.1.v201104191217 mercurialeclipse.feature.group i don't think issue mercurial eclipse java build configuration. if right-click on project , select build path -> configure build path , create sure desired source directory in sourc...

javascript - Deselecting a text box in jQuery -

javascript - Deselecting a text box in jQuery - i have jquery search script queries php file parses results html div. when no query active text box automatically selected when query active want not automatically selected. have been able disable text box isn't want. how can resolve issue? my jquery script is: $(document).ready(function(){ $('[id^=type_]').click(function(){ type=this.id.replace('type_',''); $('[id^=type_]').removeclass('selected'); $('#type_'+type).addclass('selected'); homecoming false; }); $('#type_search').click(); $('#query').keyup(function(){ var query=$(this).val(); var url='/'+type+'/'+query+'/'; window.location.hash=''+type+'/'+query+'/'; document.title=$(this).val()+' - search'; $('#results').show(); if(query=='...

Table Filtering with dropdown menu with jqGrid and php -

Table Filtering with dropdown menu with jqGrid and php - i wondering if can create similar this javascript code cause don't wanna purchase whole jgrid php library. i talk 4th column (drop downwards menu filter). i have create first grid here also read similar questions here of them based on asp .net if can achieved please give me hints.. thanks in advance. what need toolbar searching mutual searching configuration. feature exists in free open source version of jqgrid. @ the demo. hope need. php jqgrid drop-down-menu

html - Python Find & Replace Beautiful Soup -

html - Python Find & Replace Beautiful Soup - i using beautiful soup replace occurrences of pattern href link within html file i facing problem described below modified_contents = re.sub("([^http://*/s]app[a-z]{2}[0-9]{2})", "<a href=\"http://stack.com=\\1\">\\1</a>", str(soup)) sample input 1: input file contains appdd34 output file contains <a href="http://stack.com=appdd34"> appdd34</a> sample input 2: input file contains <a href="http://stack.com=appdd34"> appdd34</a> output file contains <a href="http://stack.com=<a href="http://stack.com=appdd34"> appdd34</a>"> <a href="http://stack.com=appdd34"> appdd34</a></a> desired output file 2 same sample input file 2. how can rectify problem? this may not exclusively reply problem because don't know entire input file like, hope direction can t...

java - What is the better approach to convert primitive data type into String -

java - What is the better approach to convert primitive data type into String - i can convert integer string using string s = "" + 4; // correct, poor style or string u = integer.tostring(4); // i can convert double string using string s = "" + 4.5; // correct, poor style or string u = double.tostring(4.5); // i can utilize string s = "" + data approach convert either int or double string. while if wants utilize other approach using tostring() have utilize wrapper class of each info type. why in some books mentioned first approach poor 1 while sec 1 better. which 1 improve approach , why? i use string.valueof(...) you can utilize same code types, without hideous , pointless string concatenation. note says want - string value corresponding given primitive value. compare "" + x approach, you're applying string concatenation though have no intention of concatenating anything, , empty string irrelevant y...

c++ - QSqlQuery Memory issues. QSqlQuery::exec() and QSqlDatabase::open()/close(); -

c++ - QSqlQuery Memory issues. QSqlQuery::exec() and QSqlDatabase::open()/close(); - i'm checking memory usage of application i've made. makes numerous calls read , write values , database (sqlite 3). i've observed following: qsqlquery::exec() uses kb of ram execute given query, not release memory after goes out of scope. qsqldatabase:: open() & close() not help free resources documentation suggest. if anything, close() causes resources (at to the lowest degree memory) remain 'trapped' on heap/stack. for example, here typical segment of code i've been using access database. qstringlist values; db.open(); qstring strquery = "select distinct " + field + " " + table + str; qsqlquery query(db); query.prepare(strquery); if(query.exec() == true) { while(query.next()) { values.push_back(query.value(0).tostring()); } } db.close(); having experimented find code below 'traps' less memory: qstringlist value...

c# - Using Timer inside a BackGroundWorker -

c# - Using Timer inside a BackGroundWorker - my application deals real-time data. when form opened, backgroundworker created , fetches info , processing. now entire cycle run in 5 sec loop long form active or open. ie if user opens form1 , still on in 5 secs time backgroundworker fetching , processing again. if user closes form1 , opens form2 new backgroundworker created , processing relevant form2 . i'm done backgroundworker part can't decide on how loop backgroundworker . should create timer within backgroundworker fires every 5 seconds? or chuck backgroundworker , create timer? edit: went bgw within timer. every 5 sec timer calls bgw , if bgw busy waits complete. yeah of course of study can using timer object shown below system.timers.timer timer = new system.timers.timer(); timer.elapsed += new elapsedeventhandler(timer_elapsed); timer.interval = 5000; timer.start(); private void timer_elapsed(object sender, elapsedeventargs e) { ...

ruby on rails - Getting a max/min date value from an associated model -

ruby on rails - Getting a max/min date value from an associated model - rails 2.3.5 below, (tickets :have_many => logs), i'm listing 'created_at' value of index 0. i'd max & min values field (saying 'first log 07-01-2011, lastly log entry 07-18-2011') <% @tickets.each |t| %> <% if !t.log_entries[0].nil? %> <%= t.log_entries[0].created_at %> <% end %> <% end %> <% end %> is there easy way this? tried playing around max couldn't figure out working syntax. other thing can thing of find_first asc & desc query in view. thanks ! you can rails subquery: <%= @ticket.log_entries.find(:first, :order => "created_at asc").created_at.to_s %> <%= @ticket.log_entries.find(:first, :order => "created_at desc").created_at.to_s %> happy coding :) ruby-on-rails

c# - How do I set the system time? -

c# - How do I set the system time? - on windowsxp , onwards, if set datetime hijri calendar alternative provided adjust in "regional , language options". what want either adjust hijri date using c# or set scheme date own calculated hijri scheme date? any help changing scheme datetime can done importing setlocaltime function: [dllimport("kernel32.dll")] static extern bool setlocaltime([in] ref systemtime lplocaltime); you have calculate local time based on hijri time. c# date calendar hijri

java - Jasper Reports: do not render main report when subreports have no data -

java - Jasper Reports: do not render main report when subreports have no data - situation have study consists of header , 4 subreports in detail area. subreports info querying database. requirement if subreports have no data, main study not generate - similar property "when no data" set "no pages". problem each subreport has property "remove line when blank" checked each subreport print if has data. in main report, query text "select 1 dual" print. want alter dependent on subreports, if subreports have no data, homecoming nil , hence whole study not print due "when no data" beingness set "no pages". there should way set print when look main study check subreports data, , show main study if @ to the lowest degree 1 of them does. like: if (subreport1hasdata || subreport2hasdata || subreport3hasdata || subreport4hasdata) java jasper-reports

asp.net mvc 3 - How to use a string as a primary key in MVC 3 Entity Framework 4.1 Code First? -

asp.net mvc 3 - How to use a string as a primary key in MVC 3 Entity Framework 4.1 Code First? - i'm using latest , greatest entity framework code first , i'm running scenario want 1 of classes utilize string primary key. had manually add together key create view (by default treats identity). however, when seek create new myaccount, error below. i'm using mvc scaffolder repository pattern build myaccountcontroller. wisdom seek great appreciation. model: public class myaccount { [key, required, maxlength(80), display(name = "user name")] public string username { get; set; } [required, datatype(datatype.emailaddress), maxlength(100), display(name = "email address")] public string email { get; set; } } view: <% using (html.beginform()) { %> <%: html.validationsummary(true) %> <legend>myaccount</legend> <div class="editor-label"> <%: html.lab...

mysql - Should I split a table which has big size data? -

mysql - Should I split a table which has big size data? - i'm using mysql. need save contents of xml file database. size of file less 10k. the table looks this: articles ----------- id date author ... file_name file_content (text) file_date does splitting table improve performance when select date , writer ? or there other reason split table? this called vertical partitioning. basically if total info set big (say, larger ram), , of queries not utilize big file_content data, putting in table create main table much smaller, hence much improve cached in ram, , much, much faster. of course of study retrieving file_content little slower, depends how utilize it. i used technique on forum. stored posts text (bbcode parsed html) in main table, , original posts (in bbcode) in table. when displaying forum pages, main table hit. original post text used editing posts. divided posts table size 2 , avoided having double ram on server. mysql database da...

iphone - modalViewController delegate callbacks - HowTo? -

iphone - modalViewController delegate callbacks - HowTo? - i have view controller, , when click button create modalview (wrapped uinavigationcontroller) , nowadays it. dscviewcontroller *enterdescription = [[[dscviewcontroller alloc] init] autorelease]; uinavigationcontroller* navcontroller = [[uinavigationcontroller alloc] initwithrootviewcontroller:enterdescription]; [self presentmodalviewcontroller:navcontroller animated:yes]; [navcontroller release]; the question is, how create (parent)view controller delegate, , when click on button @ modalviewcontroller (done example) phone call method in parent viewcontroller dismiss modal , savings modal input? i don't think it's practice create 1 controller blame parent controller work should handel. can utilize self.parentviewcontroller dismiss modal in. if reason handle storage in parentviewcontroller can point done button action method in current viewcontroller , utilize self.parentviewcon...

plugins - How to use/enable/setup Eclipse plug-in (Eclipse Colorizer)? -

plugins - How to use/enable/setup Eclipse plug-in (Eclipse Colorizer)? - i using eclipse 3.6.2. using "install new software" alternative in eclipse, added repository eclipse colorizer , installed plug-in. after done prompted restart eclipse, did , restarted fine. checked plug-ins directory , eclipse colorizer folder , files indeed there. however, can't life of me figure out how use/enable it. want utilize view pascal files (*.pas) colorized syntax highlighting. have searched fruitlessly through eclipse's preference settings, editor screens , dialogs, etc. can't find it. can tell me might find plug-in in eclipse can utilize it, or need able utilize it? here's link plug-in page: http://colorer.sourceforge.net/eclipsecolorer/ -- roschler eclipse plugins preferences pascal colorize

ASP.NET MVC - Any reason to use App_Themes? -

ASP.NET MVC - Any reason to use App_Themes? - is there advantage asp.net's app_themes folder taken advantage of in asp.net mvc, or using them content folder normal best way handle resources images, stylesheets, etc. does fact they're in app_themes folder add together special them? thanks, james app_themes regular asp.net, not mvc. themes scheme built on top of asp.net's event model, not used in mvc. asp.net asp.net-mvc app-themes

java - Hibernate & Tomcat -

java - Hibernate & Tomcat - i'm having problem running sample hibernate app on tomcat 7 + eclipse. app i'm running 1 provided @ hibernate.org minor changes test set up. when effort access session object server throws exception. did plug-in search on ide , not find org.hibernate.session bundle in hibernate3.jar file located in src/lib. however, eclipsed allowed import without error warnings.. stack trace: type exception study message description server encountered internal error () prevented fulfilling request. exception javax.servlet.servletexception: error instantiating servlet class core.employeemanager org.apache.catalina.authenticator.authenticatorbase.invoke(authenticatorbase.java:462) org.apache.catalina.valves.errorreportvalve.invoke(errorreportvalve.java:100) org.apache.catalina.valves.accesslogvalve.invoke(accesslogvalve.java:563) org.apache.catalina.connector.coyoteadapter.service(coyoteadapter.java:403) org.apache.coyote.http11.http11proces...

sql server - Are packages the only way to return data from an Oracle db? -

sql server - Are packages the only way to return data from an Oracle db? - i've worked sql server far , i'm moving oracle new project. i'm trying create proc homecoming info .net app. way got work using packages this: create or replace bundle getalldepartments type t_cursor ref cursor; procedure p_getalldepartments ( cur_result out t_cursor ); end getalldepartments; create or replace bundle body getalldepartments procedure p_getalldepartments ( cur_result out t_cursor ) begin open cur_result select * departments; end p_getalldepartments; end getalldepartments; is way go oracle?, can't create proc , phone call directly? thanks assuming have supported version of oracle, should able like create or replace procedure get_all_departments( p_result out sys_refcursor ) begin open p_result select * departments; end get_all_departments; that said, improve off organization standpoint using packages collect procedures...

php - My extended CodeIgniter 2.0.2 class doesn't see it's parent class methods -

php - My extended CodeIgniter 2.0.2 class doesn't see it's parent class methods - this first oop php app , i'm getting little stumped here... i created next class extends ci_model class lxcoremodel extends ci_model{ function __construct() { parent::__construct(); } public function elementexists($table,$row,$data){ $result = $this->db->select('*')->from($table)->where($row, $data)->get()->result(); if(empty($result))return false; homecoming true; } } and here class extending class above: class lxaccadminmodel extends lxcoremodel{ function __construct() { parent::__construct(); } function addaccountstatus($statusid=null, $username=null){ if($statusid==null)$statusid = $this->input->post('accountstatusid'); if($username==null)$username = $this->input->post('username'); if(elementexists('accounts','username',$username)) if(elementex...

ruby - Problems with replacing into string -

ruby - Problems with replacing into string - i'm trying execute code this: template = " ... here html tags [sitename] ... here html tags " template = template.gsub(/\[sitename\]/,"http://google.com") but it's not working. mistake? can describe how it's not working? in ruby 1.9.2 expected, command puts template gives ... here html tags http://google.com ... here html tags ruby gsub

javascript - Why is for (var i = 100; i--;) {} so much slower (70%) than for (var i = 100; i-->0;) {} in Firefox? -

javascript - Why is for (var i = 100; i--;) {} so much slower (70%) than for (var i = 100; i-->0;) {} in Firefox? - here's test: http://jsperf.com/forloopspeed as can see, difference huge in firefox, nowadays much lesser extent in safari, , absent in chrome , opera. the analogous thing happens while loops too: http://jsperf.com/whileloopspeed my guess checking whether i (a number) falsy value more computationally expensive checking true / false (the result of comparison). javascript firefox

stdout - Setting C program to line buffer won't work -

stdout - Setting C program to line buffer won't work - i'm trying forcefulness c programme line buffer (stdout going captured java program), seems buffer instead. here sample code: #include <stdio.h> #include <stdlib.h> int main(){ char c; setvbuf(stdout, null, _iolbf, bufsiz); printf("hello world\n"); c = getchar(); printf("got char: %c\n", c); } if specify _iolbf or _iofbf, don't see output until input char. if utilize _ionbf see output before getchar(). shouldn't _iolbf same since "hello world\n" contains '\n'? i using visual c++ 2005. thanks according this microsoft documentation: _iolbf: systems, provides line buffering. however, win32, behavior same _iofbf - total buffering. c stdout buffering

ios - Three20: loadView and viewDidLoad not called when restoring through TTNavigator -

ios - Three20: loadView and viewDidLoad not called when restoring through TTNavigator - when using the three20 framework have problem way how ttnavigator seems work. if in applicationdidfinishlaunching restore previous state of app with: ttnavigator* navigator = [ttnavigator navigator]; navigator.persistencemode = ttnavigatorpersistencemodeall; navigator.window = self.window; [navigator restoreviewcontrollers]; the methods loadview , viewdidload of viewcontroller restored never called. how can so? is bug or design? if it's design, fix. problem want viewcontroller load nib. i've seen other workarounds, ugly , have outside component (like app delegate instead of view controller itself) load nib, avoid. illustration of ugly workarounds given in ttnibdemo illustration ships three20 source code. it depends in way calling viewcontroller, seek in viewwillappear, should work. ios uikit three20

c++ - Using observer pattern in the context of Qt signals/slots -

c++ - Using observer pattern in the context of Qt signals/slots - i trying create design decisions algorithm working on. think want utilize signals , slots implement observer pattern, not sure of few things. here algorithm working towards: 1.) load tiles of image big file 1a.) re-create entire file new location 2.) process tiles loaded 3.) if re-create has been created, re-create resulting info new file so envision having class functions loadalltiles() emit signals tell processtile() tile ready processed, while moving on load next tile. processtile() perform calculations, , when complete, signal writeresults() new set of results info ready written. writeresults() verify copying complete, , start writing output data. does sound reasonable? there way create loadalltiles() load in tile, pass info somehow processtile() , maintain going , load next tile? thinking maybe setting list of sort store tiles ready processed, , list result tiles ready written disk. g...

view - Flex TabbedViewNavigatorApplication question about sending data -

view - Flex TabbedViewNavigatorApplication question about sending data - i have tabbedviewnavigatorapplication 3 views(viewnavigator), can utilize navigator.pushview(view,dataobject) actionscript navigate view info object of choice. how pass info object of selection when user clicks on default tab button along bottom switch views? look firstdata... allow associate info object each tab in tabbedviewnavigatorapplication. view navigation flex4.5

Android stay app active -

Android stay app active - i remain android application active when working, , using flag_keep_screen_on flag purpose, don't want maintain screen on, because it's not economic battery. want utilize standard behavior - when user touch screen - he's lighting up, , after time of inactive turn off. how can this? i suggest looking @ powermanager.wakelock , in particular powermanager.partial_wake_lock flag, maintain cpu running yet allow screen turn off. if take approach, create sure release wakelock when done it. you can find out more here: http://developer.android.com/reference/android/os/powermanager.html android

c - printf() seems to be destroying my data -

c - printf() seems to be destroying my data - i'm writing nginx module in c , having super bizarre results. i've extracted function module test output relevant nginx type/macro definitions. i'm building struct in build_key_hash_pair function, doing printf() on contents in main . when printf info within inner function, main 's output valid. when remove printf within inner function, main prints empty string. confusing because after function phone call build_key_hash_pair not operating on info except display it. here code: #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct ngx_str_t { size_t len; char *data; } ngx_str_t; typedef uintptr_t ngx_uint_t; typedef struct key_hash_pair { ngx_uint_t hash; ngx_str_t key; } key_hash_pair; #define ngx_string(str) { sizeof(str) - 1, (char *) str } #define ngx_str_set(str, text) ...

javascript - Getting list data from SharePoint 2010 site using Jquery -

javascript - Getting list data from SharePoint 2010 site using Jquery - i trying list info sharepoint site using jquery, have got nil returned yet, no errors in firebug either. clue wrong? <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var soapenv = "<soapenv:envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \ <soapenv:body> \ <getlistitems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \ <listname>action items</listname> \ <viewfields> \ <viewfields> \ <fieldref name='title' /> \ </viewfields> \ </viewfields> \ ...

c# - Linq to Entities - 3-tier Architecture -

c# - Linq to Entities - 3-tier Architecture - in past few months i've learned alot linq-to-entities , 3-tier architecture dao/dal/repository. i've few things in mind keeps bugging me. i've 3 questions you'll see below. there alot of ways create repository work way "the" way of making repository work in ways of performance. 1) initialize datacontext in constructor public class repository : irepository { private datacontext context; public repository() { context = new datacontext(); } public ilist<entity> getentities() { homecoming (from e in context.entity select e).tolist(); } } 2) use "using" public class repository : irepository { public ilist<entity> getentities() { using (datacontext context = new datacontext()) { homecoming (from e in context.entity select e).tolist(); } } } 3) in...

c# - What will happen to a var type when code block ends? -

c# - What will happen to a var type when code block ends? - what diference between 2 examples of code? public test(int x) { list<int> list= new list<int>(); list<int> list1 = new list<int>(); list= createlist(x); list1 = createlist(x + 1); dostuff(list, list1); list.clear(); list = null; list1.clear(); list1 = null; } is way code? public test(int ncount) { var list = createlist(ncount); var list1 = createlist(ncount + 1); dostuff(list, list1); } nothing. for readability , hence future maintenance reasons, utilize sec one. it's much easier understand, , because of design of c# , clr, much of code in first illustration not required. i'll seek explain mean. don't need clear or set null references local variables (the garbage collector you). need class-level fields, , not (again, garbage collector collect...

python - Any easy way to do 'mad lib' style form fields in Django? -

python - Any easy way to do 'mad lib' style form fields in Django? - i curious making "mad lib" style form (cf. http://www.lukew.com/ff/entry.asp?1007) django form. iterating on form fields , laying out text hand, e.g. <li>there should {{ form.num_widgets }} widgets</li> , dislike how label on form field unused, how it's partially spread form definition file , template file, , how it's hard i18n that. is there neater/all-in-one-place way mad lib forms in django? set label of widget "there should %(something)s widgets" , , it'll replace %(something)s rendered form of field, can phone call {{ form.as_p }} , it'll work automatically? this case custom template tag, documented here: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/ you create tag along lines of: @register.simple_tag def madlibfield(formfield): homecoming formfield.label % formfield you utilize in template {% madlibfield...

How to call a Javascript function using Cakephp -

How to call a Javascript function using Cakephp - i have function in view(aval_comp.ctp). when calculation in function on controller, want phone call javascript function. js function: <script type="text/javascript"> function calculatetotal(){ var total = document.getelementbyid('valor1').innerhtml*1 + document.getelementbyid('valor2').innerhtml*1 + document.getelementbyid('valor3').innerhtml*1 + document.getelementbyid('valor4').innerhtml*1 + document.getelementbyid('valor5').innerhtml*1 + document.getelementbyid('valor6').innerhtml*1; document.getelementbyid('total').innerhtml = total; } </script> how phone call function in controller? well talelcool not quite right. you can phone call javascript functions php highly discouraged , not how should utilize functions. php server, js client, never mix two! anyway, if in php echo out this: <?php echo ...

random - Hash randomization in Perl 5 -

random - Hash randomization in Perl 5 - when perl 5.8.1 came out added hash randomization. when perl 5.8.2 came out, thought, removed hash randomization unless environment variable ( perl_hash_seed ) present. seems if gravely mistaken as perl_hash_seed=$seed perl -mdata::dumper -e 'print dumper{map{$_,1}"a".."z"}' always kicks same key ordering regardless of value of $seed . did hash randomization go away, doing wrong, or bug? see algorithmic complexity attacks: in perl 5.8.1 hash function randomly perturbed pseudorandom seed makes generating such naughty hash keys harder. [...] of 5.8.2 is used on individual hashes if internals observe insertion of pathological data. so randomization doesn't happen, when perl detects it's needed. perl random hash

c# - Web app and mobile app to use its own public web service or not? -

c# - Web app and mobile app to use its own public web service or not? - i first built web app, , bunch of class libraries. the web app uses class librares. the mobile app uses expose public web service. now i'm thinking, since mobile app has much of same functionality of web app, maybe should create web app utilize public web service? would thought web app , mobile app utilize same public api? please help me decide , allow me know why thought or bad idea! thanks guys edit: guess if have web app utilize public api, performance may degraded? since has go thr network stack, , need provide authentication hmm .... the disadvantage of using web service web application makes slow, due request (althought both on same server) , cause performance issues. it's not thought due disadvantages. i have not tried wcf asp.net, guess improve utilize wcf asp.net through tcp protocol. without tcp, it's faster web service. c# asp.net web-services api so...

php - Best way to package a general-purpose zend module -

php - Best way to package a general-purpose zend module - as our company starts using zend framework base of operations framework of our projects, want share mutual elements across our projects. talk things like: an implementation of model (based on doctrine2) rbac model, including user, group, role models a xml-based templating engine ajax backend interfaces (you name it) ... basically, things set "zend on rails" , going. best way bundle these components? see 2 possibilities: as modules we include necessary functions separate modules modules folder. pro: we can set routes , execute code, many modules (imaginary example: paypal module needs kind of callback url. if our module can set on own, no configuration "project developer" needed). we can provide real functionality (like user administration) out of box we have bootstrap set autoloading , doctrine etc. con: bad place? interferes users project a little harder share between projects (git...

Redirecting stdout to "nothing" in python -

Redirecting stdout to "nothing" in python - i have big project consisting of sufficiently big number of modules, each printing standard output. project has grown in size, there big no. of print statements printing lot on std out has made programme considerably slower. so, want decide @ runtime whether or not print stdout. cannot create changes in modules there plenty of them. (i know can redirect stdout file considerably slow.) so question how redirect stdout nil ie how create print statement nothing? # want this. sys.stdout = none # give error nonetype object not have write method. currently thought have create class has write method (which nothing) , redirect stdout instance of class. class dontprint(object): def write(*args): pass dp = dontprint() sys.stdout = dp is there inbuilt mechanism in python this? or there improve this? cross-platform: import os import sys f = open(os.devnull, 'w') sys.stdout = f o...

c# - Animation object cannot be used to animate RenderTransform -

c# - Animation object cannot be used to animate RenderTransform - i have togglebutton i'm applying next style <style x:key="togglebuttonstyle" targettype="togglebutton"> <setter property="template"> <setter.value> <controltemplate targettype="togglebutton"> <grid> <visualstatemanager.visualstategroups> <visualstategroup x:name="commonstates"> <visualstategroup.transitions> <visualtransition generatedduration="0:0:0.1"/> </visualstategroup.transitions> <visualstate x:name="normal"/> <visualstate x:name="mouseover"> <st...

objective c - How can jump another tab with a single click on a button? -

objective c - How can jump another tab with a single click on a button? - -(void)save{ mainscreencontoller *main= [[mainscreencontoller alloc] initwithnibname:@"mainscreencontoller" bundle:nil]; [self.view.superview addsubview:[main view]]; } this place going click , button calls save function.after want application automatically turn main screen first tab bar 1 third. so click button , application switches first tab bar. try setting property of uitabbarcontroller : @property(nonatomic) nsuinteger selectedindex so first tab, like: self.tabbarcontroller.selectedindex = 0; from documentation: setting property changes selected view controller 1 @ designated index in viewcontrollers array. select more navigation controller itself, must alter value of selectedviewcontroller property instead. objective-c view uitabbarcontroller

LINQ Query: How to use WHERE to see if object exists in other query -

LINQ Query: How to use WHERE to see if object exists in other query - i using linq query various collections of info , trying build linq query checks query form results, illustration code looks this: dim myfilmresults = _ myfilm in myfilms myfilm.cert (from mycert string in mycertificationfilters select mycert) select myfilm so explain, wish homecoming collection of films included in mycertificationfilters collection. any help appreciated! :) --edit: need walk away computer , think trying achieve! can accomplish simple bring together below: dim myfilmresults = _ myfilm in myfilms bring together cert in mycertificationfilters on myfilm.cert equals cert select myfilm thanks! linq-to-objects

PayPal Payflow Pro with Chained Payments -

PayPal Payflow Pro with Chained Payments - i integrated paypal chained payments api website. wonder if there way connect payflow pro, not having roundtrip paypal's site. i think security reasons it's not possible display payment flow in modal window. payflow pro? can confirm that? thanks! mike paypal chained payflowpro

objective c - Sound Effect Not Playing -

objective c - Sound Effect Not Playing - i implementing audiotoolbox framework seek play sound effect. here code: declared systemsoundid called explode nsurl *explodeurl = [nsurl fileurlwithpath:[[nsbundle mainbundle] pathforresource:@"explosion" oftype:@"wav"]]; audioservicescreatesystemsoundid((__bridge cfurlref) explodeurl, explode); [self performselector:@selector(playsfx) withobject:nil afterdelay:2.0]; -(void)playsfx { audioservicesplaysystemsoundid(explode) } but reason sound never plays. you're calling audioservicescreatesystemsoundid , doesn't play sound, creates id it. utilize audioservicesplaysystemsound(explode); . objective-c ios xcode audio audiotoolbox

Python - capturing subprocess exceptions -

Python - capturing subprocess exceptions - i'm using os.popen(cmd) connect database isql. in unix, python version 2.3.4. i'm trying implement error handling, , i'm wondering if there's efficient way capture errors/exceptions raised called subprocesses such this, without dealing stderr, etc. thanks, dan no. whatever comes on pipe returned popen the exit code of kid process when pclose process. python

How to simulate a browser with Delphi -

How to simulate a browser with Delphi - i need build application stock exchange info on web. this, need page code , send requests (post , get). i'm trying create bot. help me please? delphi ships indy, has tidhttp , tidcookiemanager components handling http requests , replies. delphi browser bots

sql - Alter Table - add Default value for a COLUMN type BLOB -

sql - Alter Table - add Default value for a COLUMN type BLOB - executing below sql giving error . alter table table_name add together file_data blob null default 'empty_blob()' error starting @ line 37 in command: alter table table_name add together file_data blob null default 'empty_blob()' error report: sql error: ora-30649: missing directory keyword 30649.0000 - "missing directory keyword" *cause: default directory clause missing or incorrect. *action: provide default directory. could help me out ? i can either create new column of type blob , or can convert same column created varchar default value - , alter type blob . not able either of them . assuming want default value empty blob rather string 'empty_blob()', you'd need remove quotes sql> create table new_table ( 2 col1 number 3 ); table created. sql> alter table new_table 2 add( file_data blob default empty_blob() ); tab...

javascript - Open file from Playbook app -

javascript - Open file from Playbook app - my playbook app downloads zip file , opens it. so can create air objects on playbook file i/o operations since api playbook guess hasn't been developed. example: var file =new air.file(path); first, document help understand layout of playbook's file system, , directories available you, developer: http://supportforums.blackberry.com/t5/tablet-os-sdk-for-adobe-air/blackberry-playbook-file-system-layout/ta-p/773327 after that, working file can simple as: var fs:filestream = new filestream(); var f:file = file.applicationdirectory; f = f.resolvepath("myfile.txt"); fs.open(f, filemode.read); // work file contents here fs.close(); javascript blackberry air blackberry-playbook playbook

Interpolation/smoothing in Mathematica using Graphics -

Interpolation/smoothing in Mathematica using Graphics - i trying smooth path draw between points. please consider : lespoints = {{41, 26}, {42, 29}, {41, 31}, {46, 30}, {48, 30}, {40, 30}, {43, 30}, {47, 30}, {48, 26}, {47, 20}} those real eye fixations coordinates utilize trace temporal path. this way plot them : graphics[{ table[arrow[{lespoints[[i]], lespoints[[i + 1]]}], {i,length[lespoints] - 1}], mapthread[text[style[#1, large, fontfamily -> "impact"], {#2, #3}] &, prependto[transpose[lespoints], range[1, length@lespoints]]]}] i not right in effort utilize interpolation. would way smooth path, alternative ? what this lespoints = {{41, 26}, {42, 29}, {41, 31}, {46, 30}, {48, 30}, {40, 30}, {43, 30}, {47, 30}, {48, 26}, {47, 20}} interpolation = interpolation[table[{i, lespoints[[i]]}, {i, length[lespoints]}]] the path becomes like plot = parametricpl...

c# - How to send a click from a form to a form -

c# - How to send a click from a form to a form - i have windows-mobile programme has 2 forms. in form1, have textbox , in form2, have 5 buttons. how when press buttons in form2 i'll see them on textbox in form1 create public property on form allow calling form access chosen value. public partial class selectionform : form { public selectionform() { initializecomponent(); } //selection holder private string _selection; //public access item public string selection { { homecoming _selection; } } private void button1_click(object sender, eventargs e) { _selection = "one selected"; this.close(); } private void button2_click(object sender, eventargs e) { _selection = "two selected"; this.close(); } } then calling form can obtain value before form disposed. public partial class textform : form { public textform() { initializecompone...

wcf - App.Config not being read -

wcf - App.Config not being read - i trying test class in service handler using nunit project. service handler class part of class library project gets info wcf service. when phone call test project method comes service handler class , method in class tries creat clients object statement - using (client client = new client()), throws exception : "could not find default endpoint element references contract 'xyz' in servicemodel client configuration section. might because no configuration file found application, or because no endpoint element matching contract found in client element." loos app.config file not beingness read in case, thats why exception coming. has ever faced issue? need urgent help regarding this. add app.config nunit assembly. add together wcf service client config app.config , should work. wcf nunit app-config

dom manipulation - remove 3 last divs with jQuery -

dom manipulation - remove 3 last divs with jQuery - <div id="widgetareafooter"> <div class="row">1</div> <div class="row">2</div> <div class="row">3</div> <div class="row">4</div> <div class="row">5</div> <div class="row">6</div> <div class="row">7</div> </div> how remove 3 lastly div ? i tryed doesn't work :/ var row = $( '#widgetareafooter>.row' ); var nbr = row.length ; ( var i=4;i<nbr;i++ ) row.get(i).remove(); or ( var i=4;i<nbr;i++ ) row[i].remove(); this remove lastly 3 elements: $('#widgetareafooter > .row').slice(-3).remove(); jsfiddle demo you can part of jquery collection using .slice() . if negative number provided, indicates position starting end of set, rather beginning. jquery dom-manipulation dom-traversal

windows - Reproduce ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 error code from ReplaceFile -

windows - Reproduce ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 error code from ReplaceFile - i using replacefile win32 function part of operation atomic behaviour. of 3 special error codes function, i've been able reproduce , recover (rollback) two: error_unable_to_move_replacement , error_unable_to_remove_replaced. my questions relate 3rd error code: error_unable_to_move_replacement_2. has seen error code returned? under conditions possible? any ideas on how repoduce error can test path in code recovers it? i gather documentation recover (rollback) error, need rename replaced file original name, because replacefile have left backup file name. can verify in fact state replacefile leaves files in? some more details in case helps: replacefile called non-null backup file name (in fact error_unable_to_move_replacement_2 cannot occur if null backup name given). i pass replacefile_write_through flag. the files exist on same ntfs volume. error_unable_to_move_replacement_2...

asp.net mvc - MVC Radiobutton binding complex object -

asp.net mvc - MVC Radiobutton binding complex object - i have mvc3 web application need populate radio button list validation. model this: public class employeesviewmodel { public list<employee> listemployee { get; set; } //to persist during post public ienumerable<selectlistitem> selectlistemployee { get; set; } [required] public employee selectedemployee { get; set; } } public class employee { public int id {get; set;} public string name {get; set} public string section {get; set} } i need populate radiobutton list below: employee1id - employee1name - employee1department // id - name - department employee2id - employee2name - employee2department employee3id - employee3name - employee3department selected employee should stored "selectedemployee" field. best or clean way populate these radio button list in mvc3? note: looking 2 task: 1. storing "employee" object in each "input" radio butto...

java - New SimpleCursorAdapter whenever data changes? -

java - New SimpleCursorAdapter whenever data changes? - i'm starting out android development , have been building simple app uses listactivity , sqlitedatabase , , simplecursoradapter . on android developer website there illustration project demonstrates usage of simplecursoradadpter . looking @ implementation, whenever underlying database modified result of user action, listactivity explicitly calls next function "refresh" list: class="lang-java prettyprint-override"> private void filldata() { // of rows database , create item list mnotescursor = mdbhelper.fetchallnotes(); startmanagingcursor(mnotescursor); // create array specify fields want display in list (only title) string[] = new string[]{notesdbadapter.key_title}; // , array of fields want bind fields (in case text1) int[] = new int[]{r.id.text1}; // create simple cursor adapter , set display simplecursoradapter notes = new simplecursoradap...

css - Designing a Page for Screen and Print Medias - Font-Size -

css - Designing a Page for Screen and Print Medias - Font-Size - i've created study shown on screen , should printable well. application has back upwards ie 6.0 too. what font-sizes should using? i've read, should using em screen media (web page) , pt print media (i know em scalable , pt isn't...). how design such page in terms of css elements? e.g. creating separate css file print media , duplicating css classes there , modifying font-size? much duplication. isn't there improve way? thanks you don't need duplicate much. create study web. then, in body of stylesheet add together reference print styles, so @media print { div#content {background:#fff; width:90%; font-family:serif; font-size:12px;} div#header, div#insideheader, div#topnav, div#footer, div#navcontainer, p.pic img {display:none;} div#main {border:none; background:none;} {color:black;} } in illustration above, setting background-color white , extending conten...

javascript - JQuery resizeable and dragable divs positioning problems -

javascript - JQuery resizeable and dragable divs positioning problems - i'm having problem positioning divs within larger div , having them behave want. the source , preview here: http://jsbin.com/usuniw/6/edit problem 1 when hidden div unhidden appears under div want appear inside. 1 time dive within resized (using handle on left hand side) pops place problem 2 when resizing hidden div moves outside boundry of it's parent rather aligning right-hand side of it. thanks help can give. at moment, have #selectedresult element set float right causing appear underneath #ipad element. if rid of float:right on #selectedresult , instead set to: position: absolute; right:0; top:0; and set #ipad element to: position:relative; then element fixed top , right sides of parent. you can see updated version of illustration here: http://jsbin.com/uxavov/edit#preview javascript jquery-ui html draggable resizable

validation - jQuery to trim() a text input field's value attribute? -

validation - jQuery to trim() a text input field's value attribute? - in jqeury, i'm able bind paste event validate form field, method within function apparently wrong. i'm not getting alert @ all. i want trim text that's input , homecoming value of form input text field #adsense_client_id. $("#adsense_client_id").bind('paste', function(e) { $(this).attr('value') = $.trim(this).val(); alert($(this).val()); //why no alert? }); the $.trim function needs variable/string within it, since did not wrap $(this).val() $.trim in order work. as need timeout paste caught, this: $("#adsense_client_id").bind('paste', function(e) { var clientid = $(this); settimeout(function(){ clientid.val($.trim(clientid.val())); alert(clientid.val()); }); }); demo. jquery validation

Is it possible to reserve the size of a hash table in Perl? -

Is it possible to reserve the size of a hash table in Perl? - i'm creating hash table in perl, of unknown size. the hash table maps string reference array. the main loop of application adds 5-10 elements hash table in each iteration. hash table fills up, things start slow downwards drastically. observation, when there ~50k keys in hash table, adding keys slows magnitude of 20x. i postulate hash table has become full, , collisions occurring. 'reserve' size of hash table, i'm unsure how. the hash in question hngramstoword. for each word, 1-len-grams of word added keys, reference array of words contain ngram. for example: addtongramhash("hello"); [h, e, l, l, o, he, el, ll, lo, hel, llo, hell, ello, hello ] added keys, mapping "hello" sub addtongramhash($) { $word = shift; @angrams = makengrams($word); foreach $ngram (@angrams) { @awords; if(defined($hngramstoword{$ngram})) { @awords = @{$hn...