Posts

Showing posts from January, 2013

Creating a jar file in Android -

i want create jar file own classes. can give me sample code creating simple jar file in android? check creating jar file .class file in bin folder

c# 4.0 - How is the long method way of doing below code in "Lambda Expressions" in the past? -

public static ienumerable<t> get<t>(this ienumerable<t> source, func<t, bool> predicate) { foreach (t item in source) { if (predicate(item)) yield return item; } } like this: public static ienumerable<t> get<t> (ienumerable<t> source, func<t, bool> predicate) { var list = new list<t>(); foreach (t item in source) { if (predicate(item)) { list.add(item); } } return list; }

Java Swing - Problem in disabling JCheckbox -

i disabling jcheckbox , enabling of setenabled(...) method. but problem if disable unselected checkbox, becomes selected after enable it. i want of them have same state after being enabled had before being disabled. are enabling/disabling jcheckbox using actionlistener? if so, normal because when click on checkbox, isselected() status changes. what can add checks using isselected() , setselected() methods.

Problem passing json into jquery graph(flot) -

i trying retrieve json pass flot graph. know json right because hard coded check, i'm pretty sure i'm not passing right because it's not showing up. here's javascript: var total = $.ajax({ type: "post", async: false, url: "../api/?key=xxx&api=report&crud=return_months&format=json" }).responsetext; //var total = $.evaljson(total); var plot = $.plot($("#placeholder"),total); here's json: [ { data: [[1,12], [2,43], [3,10], [4,17], ], label: "e-file"}, { data: [[1,25], [2,35], [3,3], [4,5], ], label: "bank products" }, { data: [[1,41], [2,87], [3,30], [4,29], ], label: "all returns" } ], {series: {lines: { show: true },points: { show: true }}, grid: { hoverable: true, clickable: true }, yaxis: { min: 0, max: 100 }, xaxis: { ticks: [[1,"january"],[2,"february"],[3,"march"],[4,"april"],[5,"may"],[6,"june"],[7,"july"]...

ruby on rails - Why is my new ID always "1" -

i have parent-child relationship between 2 objects. parent :has_many :children child :belongs_to :parent when creating new parent, in same controller, i'm creating child. @mom = parent.new @child = child.new @mom.children << @child that seems go okay, parent has 1 more attribute - parent has favorite child @mom.favorite_child = @child seems should work, except let's 61st child in database, gets id of 61 (and know happening, because when check database, child record has id of 61). reason, when assign @child parent's "favorite_child" attribute, "favorite_child" gets set "1" - when need set "61". clues? seems parent needs like class parent has_many :children has_one :favorite_child, :foreign_key=>'favorite_child_id', :class_name => 'child' otherwise, doesn't know it's foreign key relationship, , you're trying assign object integer.

c# - VS2005: Found conflicts between different version of the same dependent assembly -

what mean if receive warning? mean project referencing same assembly different files? this can commonly occur if "project reference" has somehow reverted file reference. if have project referencing other projects, try removing references , re-adding them. can occur if 2 dependent projects each reference different version of third assembly.

How to use LINQ in Mono? -

i can't make system.linq (aka linq objects) work. running monodevelop 2.2.1 in ubuntu 10 lucid lynx mono 2.4.4. they advertise in site implemented linq, can't find enumerable.range or toarray() . what's wrong? i guess need is: in project options set "runtime version" "mono/.net 3.5" add reference system.core package (right click references in solution explorer) add "using system.linq" module after code should compile , execute hope helps, regards

javascript - jQuery plugin options: required, optional, inaccessible -

i'm curious how specify options jquery plugin in way required, optionally overridden, , can't touched. i started off usual: jquery.fn.plugin = function (options){ var defaults = { username: "", posts:10, api: "http://myapi.com" } var settings = jquery.extend({}, defaults, options); } let's want username required, posts optional (defaults 10) , (you being user of plugin) can't change api , if try. ideally, they'd still in same data structure instead of being split separate objects. ideas? if wanted username required, i'd make parameter, given it's required thing , there aren't 20 parameters want way. this: jquery.fn.plugin = function (username, options){ var defaults = { posts:10, api: "http://myapi.com" } var settings = jquery.extend({}, defaults, options); } there's not clean required way completely in single passed object, @ least not simple one, want api. alternative specify no de...

How to get the selected new page size of telerik's radlistview -

we need save selected new page size session. we have tried pagesizechanged event newpagesize returns 0. is there way new page size value? how? thanks. i able need protected void page_load(object sender, eventargs e) { int newpagesize = ((raddatapager)radlistview1.findcontrol("raddatapager1")).pagesize; if ((int)session["imagesperpage"] != newpagesize) { session["imagesperpage"] = newpagesize; } radlistview1.pagesize = (int)session["imagesperpage"]; } this seems kind of hack. other more elegant ways this?

c# - asp net mvc validation and ViewModel -

i have 4 layer solution medium size project: model (ef poco entities) data (ef objectcontext) services asp net mvc question a)should have validation attributes- dataanotation in models or mvc project? b)where should set viewmodel-s if in mvc fill viewmodels data, in controller? else if on other project should create repository vewmodel? c) should viewmodel have validation>? a, c) if have view models different dtos, might prefer use dataannotations in both types. way, can validate before try persist , again persist in case dtos used outside scope of mvc app. b) tuck view models models folder of mvc app , dtos data project separate mvc app. use automapper lot copy values between view models , dtos.

FineTune TSQL SQL Server -

the below query takes lot of time, 80 minutes return 1400 results, recommendation how tune exec sp_executesql n'set arithignore on; select top (@solutionid) b.[solutionid],max(b.title) title, min(a.[status]) [status], min(a.[audience]) audience, max(b.productname) productname, min(cast( datecreated datetime)) datecreated , min(cast( datelastmodified datetime)) datemodified, [pc_pres_text]=replace(replace(replace((select [pc_pres_text] [data()] [dbo.view] a.[solutionid]=b.[solutionid] xml path('''')), ''&lt;'',''<''),''&gt;'',''>'') ,''&amp;'',''&''), ''http://support/supp=''+b.[solutionid] primusurl [view] b inner join [table] on b.solutionid=a.solutionid ((@audience null , [audience] null) or [audience] @audience) , [datecreated] > @datecreated , ...

postgresql - Updating duplicates from one-to-many relationships. -

this isn't standard "how find duplicates" question, know how find duplicates, see below. question how update said records have child items matching records? alright, i'm going give whole scenario can work problem. duplicate records inserted result of critical system failure. finding later duplicates , marking parent commission_import_commission_junction "is_processed = true" solves problem. the complication commission_import_commission_junction , children commission_import_commission_junction_line_items must identical on columns compare. the tables are: commission_import_commission_junction - id - created_date - columns checked duplication - columns not checked duplication commission_import_commission_junction_line_items - id - columns checked duplication - columns not checked duplication (for full table spec, check out create table statements in bottom-most block of code.) the query mark duplicates on parent table commission_impo...

How to set timeout on python's socket recv method? -

i need set timeout on python's socket recv method. how it? the typical approach use select() wait until data available or until timeout occurs. call recv() when data available. safe, set socket non-blocking mode guarantee recv() never block indefinitely. select() can used wait on more 1 socket @ time. import select mysocket.setblocking(0) ready = select.select([mysocket], [], [], timeout_in_seconds) if ready[0]: data = mysocket.recv(4096) if have lot of open file descriptors, poll() more efficient alternative select() . another option set timeout operations on socket using socket.settimeout() , see you've explicitly rejected solution in answer.

mysql - Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in PHP -

mysql_connect("localhost","root",""); mysql_select_db("hitnrunf_db"); $result=mysql_query("select * jos_users outfile 'users.csv' fields escaped '""' terminated ',' enclosed '"' lines terminated '\n' "); header("content-type: text/plain"); header("content-disposition: attachment; filename=your_desired_name.xls"); header("content-transfer-encoding: binary"); header("pragma: no-cache"); header("expires: 0"); print "$header\n$data"; in above code in query string i.e string in side mysql_quey we getting following error parse error: syntax error, unexpected t_constant_encapsed_string in c:\wamp\www\samples\mysql_excel\exel_outfile.php on line 8 in query string '\n' charter not identifying string thats why above error getting you need escape double quote as: \" instead of "" $re...

c# - Lambda Expression to be used in Select() query -

i trying build lambda expression, containing 2 assignments (as shown further down), can pass queryable.select() method. i trying pass string variable method , use variable build lambda expression can use in linq select query. my reasoning behind have sql server datasource many column names, creating charting application allow user select, typing in column name, actual column of data want view in y-axis of chart, x-axis being datetime. therefore, can choose data chart against datetime value (it’s data warehouse type app). i have, example, class store retrieved data in, , hence use chart source of: public class analysischartsource { public datetime invoicedate { get; set; } public decimal yvalue { get; set; } } i have (purely experimentaly) built expression tree clause using string value , works fine: public void getdata(string yaxis) { using (dataclasses1datacontext db = new dataclasses1datacontext()) { var data = this.functionone().asqueryable...

c# - Populate two column grid with databinding? -

how populate 2 column grid objects observable collection? i've tried achieve effect using tookits wrap panel items stack. <toolkit:wrappanel margin="5,0,0,0" width="400"> <itemscontrol itemssource="{binding trips}"> <itemscontrol.itemtemplate> <datatemplate> <stackpanel height="236" width="182"> <button style="{staticresource vasttrafikbuttontrip}"> <stackpanel width="152" height="140"> <textblock text="{binding fromname}" /> <textblock fontfamily="segoe wp semibold" text="till" /> <textblock text="{binding toname}" /> </stackpanel> </button> <textblock h...

How to use onPause with Android? -

Image
using onsaveinstancestate(bundle ..) , onrestoreinstancestate(bundle ..) , work, working when click turn off button on emulator. now, want save state , restore saved data when below button used: i think possible use onpause() or oonstop(), if right, how use it, enough show me java source of saving 1 boolean variable, , restore it, thanks. i use onpause() , onstop() not guaranteed called. see application fundamentals details on lifecycle. to save , restore boolean, use sharedpreferences . there code example on data storage page shows how save , restore boolean. use oncreate() , onstop() , use onresume() , onpause() , reasons have mentioned.

hash sign in facebook urls -

i wonder, why facebook.com (hypem.com, etc.) choose hash sign after domain path other files. http://www.facebook.com/#!/reqs.php#event (#!/reqs.php). what reason, , map them javascript? google explains here: http://code.google.com/intl/en-us/web/ajaxcrawling/ http://code.google.com/intl/en-us/web/ajaxcrawling/docs/learn-more.html

Drupal: new content module for manage lists -

does known module new content type "lists", module webforms used manage different web forms, ("lists") manage different lists. for example, admin create content of "lists" (something this.../node/add/list), set minimum: name, title , other common things; fields of every record in list (like fields in webforms); setup hierarchy (how many level deep). user can manage created list (.../node/???): add/delete folders (for hierarchy); add/delete records in folders (or root) fills fields; move records betweens folders; browse list. p.s. try search on drupal.org word "list" "garbage" , cannot find suitable. checkout nodequeue module. closest description http://drupal.org/project/nodequeue

android - Porting a Google Maps app to Osmdroid - problem with overlay -

i'm porting google maps based project osmdroid in order use openstreetmaps. port working ok apart adding overlay consists of number of straight lines , text. in both projects add overlay means of timer thread , handler calling redrawoverlay. in osm project overlay grey square hiding map. if remove call redrawoveraly, osm tiles shown ok. i've reduced overlay code bare minimum of single diagonal line in code samples below. works fine in google app, overlaying map tile. com.google.android.maps.overlay has draw method, osm has ondraw, have in osm version: private mapview mv; private mapoverlay mmapoverlay = null; private void redrawoverlay() { gpt = mv.getmapcenter(); if (mmapoverlay == null) mmapoverlay = new mapoverlay(getapplicationcontext()); list<overlay> listofoverlays = mv.getoverlays(); listofoverlays.clear(); listofoverlays.add(mmapoverlay); mv.invalidate(); } public class mapoverlay extends org.osmdroid.v...

javascript - A quick question on data returned by jquery.ajax() call (EDITED) -

edit: original problem due stupid syntax mistake somewhere else, whicj fixed. have new problem though, described below i have following jquery.ajax call: $.ajax({ type: 'get', url: servicesurl + "/" + id + "/tasks", datatype: "xml", success : createtasklisttable }); the createtasklisttable function defined as function createtasklisttable(tasklistxml) { $(tasklistxml).find("task").each(function(){ alert("found task") }); // each task } problem is: doesn't work, error saying tasklistxml not defined. jquery documentation states success functions gets passed 3 arguments, first of data. how can pass data returned .ajax() function variable name of own choosing. my problem i'm getting xml previous ajax call! how possible? previous function defined function convertservicexmldatatotable(xml) , don't use same variable name. utterly confused. caching issue? if so, h...

python - How to delete an item in a list if it exists? -

i getting new_tag form text field self.response.get("new_tag") , selected_tags checkbox fields self.response.get_all("selected_tags") i combine them this: tag_string = new_tag new_tag_list = f1.striplist(tag_string.split(",") + selected_tags) ( f1.striplist function strips white spaces inside strings in list.) but in case tag_list empty (no new tags entered) there selected_tags , new_tag_list contains empty string " " . for example, logging.info : new_tag selected_tags[u'hello', u'cool', u'glam'] new_tag_list[u'', u'hello', u'cool', u'glam'] how rid of empty string? if there empty string in list: >>> s = [u'', u'hello', u'cool', u'glam'] >>> = s.index("") >>> del s[i] >>> s [u'hello', u'cool', u'glam'] but if there no empty string: >>> s = [u'he...

module - DotNetNuke Starter Kit Version 05.06.01 creates an old manifest file -

i installed starter kit version 05.06.01 on visual studio 2010 , when create compiled module, first line of manifest file is: <dotnetnuke version="3.0" type="module"> shouldn't version 5.0 thanks. starter kit's manifest uses older "module" manifest type, current version 3.0. not related dotnetnuke major version, or version of module described in manifest. module manifest type used package modules, , compatible dnn4 , dnn5. in dnn5 better use manifest type "package", version 5.0. more specifically, "package" manifest type used new extension installer . "package" type can used install extensions: modules, skins, authentication providers, , on. package manifest type not compatible dnn4, 1 exception, authentication providers (since 4.6.2). starter kit has not been updated new package system yet, can try christoc's dotnetnuke module development template dnn5 manifests.

uitableview - ios steps to create custom UITableViewCell with xib file -

i need create own uitableviewcell using xib file, draw graphic interface... right steps create new class , use uitableview? thanks in advance in ios5 you'll want use new: registernib:forcellreuseidentifier : which same thing...

unit testing - Using content from the project in tests -

i working visual studio 2010 , it's integrated testing functionality. have xml file in project set copy output directory. can access file fine when compile , run project. doesn't exist when attempt access within testmethod. it looks test run working directory set "out" directory created within testresults directory. can set breakpoint before use file. if copy file "out" directory , continue running test accesses file properly. not how want automated tests function. is possible tell vs copy build directory working directory? i found of solution. though i'm not happy it. under test -> edit test settings edit current settings. under deployment tab, check enable deployment checkbox. in additional files , directories deploy add bin\debug directory (looks src\localmodels.test\bin\debug) i suppose add each file need , bit faster. seems bit ridiculous.

django - How to filter Many2Many / Generic Relations properly with Q? -

i have 3 models, taggedobject has genericrelation objecttagbridge. , objecttagbridge has foreignkey tag model. class taggedobject(models.model): """ class represent tagged object """ tags = generic.genericrelation('objecttagbridge', blank=true, null=true) class objecttagbridge(models.model): """ connect generic object tag. """ # pylint: disable-msg=w0232,r0903 content_type = models.foreignkey(contenttype) object_id = models.positiveintegerfield() content_object = generic.genericforeignkey('content_type', 'object_id') tag = models.foreignkey('tag') class tag(models.model): ... when attaching tag object, creating new objecttagbridge , set foreignkey tag tag want attach. working fine, , can tags attached object easy. when want (filter) objects have tag1 , tag2 tried this: query = q(tags__tag=t...

php website url matching question -

i new php site, familiar .net web forms sites. i can't figure out how routing working on php site. www.oursite.com/suggestions.php suggestions.php www.oursite.com/suggestions loads php fine www.oursite.com/suggestions/ loads php, no css applied www.oursite.com/suggestions/anything - comes after '/' ignored , suggestions loaded without css. oursite.com/suggestions////// works, oursite.com/suggestions/2/2/2/2/whatever i have searched not found explanation on how working. can explain or provide resource? thank you. this done using mod_rewrite, apache extension. you'll find file called .htaccess in public root, in these rewriting rules defined.

c++ - Opt-out of copy constructor -

this might silly question, but... i've been writing number of classes utilize non-copyable members. these classes never initialized via copy constructor in source. when try compile without supplying own copy-constructor, g++ throws out many errors how can't build default copy constructor, due non-copyable member objects. is there way tell compiler not give me copy constructor? edit: yeah... feels silly ... had case invoking copy-constructor accident in boost::bind call. lesson learned. if don't cause copy-constructor called not error if compiler unable generate one. sounds (possibly indirectly) causing copy-constructor used. you can suppress compiler generated 1 declaring own copy-constructor (you don't need define if you're not using it). can place in private section of class. if changes error copy-constructor inaccessible or link errors causing copy-construtor used , need analyze why is.

Problem reading text files without extensions in python -

i have written piece of code supposed read texts inside several files located in directory. these files text files not have extensions.but code not able read them: corpus_path = 'reviews/' infile in glob.glob(os.path.join(corpus_path,'*.*')): review_file = open(infile,'r').read() print review_file to test if code works, put dummy text file, dummy.txt. worked because has extension. don't know should done files without extensions read. can me? thanks just use * instead of *.* . the latter requires extension present (more precisely, there needs dot in filename), former doesn't.

java - SerialVersionUID with "private static final long" still gets InvalidClassException -

i have compiled , jarred various projects in java application, generating serialversionuids automatically through eclipse classes derived serializable. i read answers question , , verified serialversionuids private static final long . nevertheless, error when try run: java.io.invalidclassexception: com.acme.product.widget; local class incompatible: stream classdesc serialversionuid = 5226096973188250357, local class serialversionuid = -5432967318654384362 what missing? you have classpath issue, program resolving older incompatible version of class has different value serialversionuid. or serialized object being loaded, serialized oder version of class unavailable.

sqlplus - Oracle - timed sampling from v$session_longops -

i trying track performance on procedures run slow (and seem keep getting slower). using v$session_longops track how work has been done, , have query ( sofar/((v$session_longops.last_update_time-v$session_longops.start_time)*24*60*60) ) tells me rate @ work being done. what i'd able capture rate @ work being done , how changes on time. right now, re-execute query manually, , copy/paste excel. not optimal, when phone rings or else happens interrupt sampling frequency. is there way have script in sql*plus run query evern n seconds, spool results file, , continue doing until job ends? (oracle 10g) tanel poder's snapper script wonderful job of actively monitoring performance. has parameters for <seconds_in_snap> - number of seconds between taking snapshots <snapshot_count> - number of snapshots take ( maximum value power(2,31)-1 ) it uses pl/sql , call dbms_lock.sleep

Managing hdfs in pseudo-distributed hadoop mode -

i want computation hadoop , mahout on quad core machine, using hadoop in pseudo-distributed mode. the problem space on root drve limited, how can configure use space available on other external hard drive. you can configure hdfs strores data. add following conf/hdfs-site.xml: <property> <name>dfs.data.dir</name> <value>__path_to_where_you_want_to_store_your_data/hdfs/data/</value> </property> <property> <name>dfs.name.dir</name> <value>__path_to_where_you_want_to_store_your_data/hdfs/name/</value> </property> after theese changes have format namenode: hadoop namenode -format

authentication - Why has my ASP.NET single sign-on stopped working? -

i have .net 2.0 web application acts authentication stub older .net 1.1 web app. user logs in via 2.2 app , gets redirected 1.1 app business. had used technique described scott guthrie , matching machine keys in local web.config files, auth ticket readable both applications. technique has worked me in 5 instances couple of years. until now. as of morning 4 of our paired applications, configured described above, have stopped working in production: bounced after (seemingly) successful authentication attempt. during login attempt bounced login page. i've checked event logs , iis logs , found nothing of consequence. can see auth cookie has been set in our browsers. we've tried multiple browsers (ie , chrome). on weekend know more dozen patches installed on web server, 1 of added framework 4.0, have no way of knowing whether of these patches caused problem. interestingly, noticed same behavior on dev box before christmas. since time none of 4 paired applications has been re-...

visual studio 2010 - Accessing IIS 7.5 Express from another machine on the intranet -

i running on vs 2010 pro sp1 beta , iis 7.5 express. working fine, trying access site machine on our intranet , not seem see anything, a: "oops! link appears broken." error in chrome. if on machine , type in: 123.45.6.8/sitename instead of: localhost/sitename (which works), error. can done iis 7.5 express? thank you. iis express default supports local connections - according statement scottgu, there should option explicitly enable remote connections, however. see blog post: serving external traffic webmatrix how this.

Redesign using State Design Pattern -doubts -

i want redesign code using state design pattern. states belong specific objects. example: class can have 3 states: st1, st2, st3. similarly, class, b, can have 2 states: st4, st5. there case class c has 1 state: st1 , st4 , st5. basically these states should interchangeable in case of complex objects. also, these classes a, b, , c contain data specific them used states. my question is : how should state machine designed? should there individual sm every class? can states have common base interface? please me out; can ask me more questions if need more info. my question how should state machine designed ,should there individual sm every class ? if understand description, answer "yes", each object require own state machine. can states have common base interface ? a common interface implies common api multiple implementations. common methods each state have, , how implementations differ state? you may not need class each state...

django customizing form labels -

i have problem in customizing labels in django form this form code in file contact_form.py: from django import forms class contactform(forms.form): def __init__(self, subject_label="subject", message_label="message", email_label="your email", cc_myself_label="cc myself", *args, **kwargs): super(contactform, self).__init__(*args, **kwargs) self.fields['subject'].label = subject_label self.fields['message'].label = message_label self.fields['email'].label = email_label self.fields['cc_myself'].label = cc_myself_label subject = forms.charfield(widget=forms.textinput(attrs={'size':'60'})) message = forms.charfield(widget=forms.textarea(attrs={'rows':15, 'cols':80})) email = forms.emailfield(widget=forms.textinput(attrs={'size':'60'})) cc_myself = forms.booleanfield(required=false) the view using in l...

Simulating a POST with PHP & cURL -

i'm trying simulate post website based on see coming live http headers in firefox. here's copy/paste of log firefox plugin: post /context?tab=login http/1.1 host: website user-agent: mozilla/5.0 (x11; u; linux i686; en-us; rv:1.9.2.13) gecko/20101206 ubuntu/10.10 (maverick) firefox/3.6.13 accept: text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip,deflate accept-charset: iso-8859-1,utf-8;q=0.7,*;q=0.7 keep-alive: 115 connection: keep-alive referer: referer cookie: fontsize=2; jsessionid=0000pxe_bk7tjzfzeynhqokzxz2:-1 content-type: application/x-www-form-urlencoded content-length: 46 loginid=password&password=password&login=login and response follows after post: http/1.1 302 found location: website/context?tab=p00689 content-language: en-us set-cookie: jsessionid=0000oaklieedrwkx5yciju5v1lm:-1; path=/ transfer-encoding: chu...

MySQL/PHP Determine lowest values in table with multiple value columns -

ok have table columns like id, name, c_price1, p_price2, c_price3, p_price4 i need figure out mysql query search c_price1 & c_price2 columns , return lowest 5 values within table not equal 0.00 your appreciated. use least function : select least(t.c_price1, t.c_price2) lowest your_table t least(t.c_price1, t.c_price2) != 0.00 order lowest limit 5 can't use column alias in clause, earliest mysql supports group that's not case databases.

How to sign in a user using Devise from a Rails console? -

after loading rails console, how should sign in user? devise provides test helper can used in tests , i've tried use in console: >> include devise::testhelpers >> helper.sign_in(user.first) but get: nomethoderror: undefined method `env' nil:nilclass anyway, use real devise helper , not test helper. there way achieve this? here's 1 way able it: >> applicationcontroller.allow_forgery_protection = false >> app.post('/sign_in', {"user"=>{"login"=>"login", "password"=>"password"}}) then can do: >> app.get '/some_other_path_that_only_works_if_logged_in' >> pp app.response.body

serialization - How to Serialize CookieContainer in wp7 applications? -

i tried serialize cookie save , deserialize @ next time start application.but result of deserialize empty.what's wrong? void savecookie() { var appstorage = isolatedstoragefile.getuserstoreforapplication(); if (this.checkbox_save_passowrd.ischecked == true) { cookiecontainer cc = sec_services.httprequest.cookie; string filename = "usercookie.xml"; using (var file = appstorage.openfile(filename, system.io.filemode.openorcreate, system.io.fileaccess.write)) { using (var writer = new streamwriter(file)) { system.xml.serialization.xmlserializer xs = new system.xml.serialization.xmlserializer(typeof(cookiecontainer)); xs.serialize(writer, cc); writer.close(); } } } else { if (appstorage.fileexists("usercookie.xml")) { appstorage.deletefile("usercookie.xml"); } } } void ...

templates - Use 'now' in django blocktrans? -

i'd add year django blocktrans - using syntax below. {% blocktrans now|date:"y" copydate %} &copy; {{ copydate }} company {% endblocktrans %} this similar existing django ticket (http://code.djangoproject.com/ticket/3088), apparently should work can't work either. in both cases tag not expanded, rest of blocktrans renders fine. the way date in python , use date filter reiner proposes or define own templatetag. can create little context processors set date in context. def my_date(request):   import datetime   return {'my_date':datetime.datetime.now()} and add in settings.py template_context_processors = default_settings.template_context_processors + ( 'the_package_of_my_tiny_function.my_date', ) use in templates this: {% blocktrans my_date|date:"y" copydate %} © {{ copydate }} company {% endblocktrans %} don't forget pass requestcontext context_instance in views here exampl...

c# - ThrowException does not exists in the current context -

doing practice in vs2010. working try/catch/finally , getting following message: throw exception not exists in current context. missing using statement use throwexcpetion? using system; using system.collections.generic; using system.linq; using system.text; class program { static string[] etypes = { "none", "simple", "index", "nested index" }; static void main(string[] args) { foreach (string etype in etypes) { try { console.writeline("main() try"); console.writeline("throwing: \"{0}\") called.",etype); throwexception(etype); console.writeline("main() try continuing"); } catch (system.indexoutofrangeexception e) { console.writeline("main system.indexoutofrange catch", e.message); } ...

oop - Javascript pushing object into array -

hey, having trouble trying work. here's sample code of trying. lot has been taken out, should still contain problem. have object, user, , array, player. trying make array players in it, here: function user(name, level, job, apparel) { this.name = name; this.state = "alive"; this.level = level; this.job = job; this.apparel = apparel; } player = new array(); player.push(new user("main player", 1, 1, "naked")); document.write(player[0].name); but it's not working, nothing's being echo'd. doing wrong? i player = []; instead of player = new array(); as sanity check, try doing: document.write("name: " + player[0].name);

.NET Memory profiler wanted -

i need memory profiler .net, ideal if shown types of objects loaded in memory. use dottrace not seem show object types. have looked @ ants memory profiler redgate?

multiple columns - Latex multicolumn problems -

i trying build table in latex 5 columns have common title centered above columns. generated table not appear expected. (the common title left justified instead of centered above columns) the code looks like \documentclass{article} \begin{document} \begin{table} \centering \begin{tabular}{|l|c|c|c|r|} \multicolumn{5}{c}{hydrotalcite} \\ \hline kalhsdfsa & 1 asdf asf asfa &7as dfas fasdf as0 & 003 \\ kalhsdfsa & 1 asdf asf asfa &7as dfas fasdf as0 & 003 \\ kalhsdfsa & 1 asdf asf asfa &7as dfas fasdf as0 & 003 \end{tabular} \caption{lala} \label{tabtablerefereasdasdnce} \end{table} \end{document} and i'm running miktex 2.8 on windows xp your multicolumn amount 1 high change \multicolumn{4}{c}{hydrotalcite} \\\hline (in stead of \multicolumn{5}{c}{hydrotalcite} \\\hline ) or add fifth column ;-)

http status code 404 - Joomap (on joomla) causes 404 error if it is menulink case -

i'm using joomla 1.5 , installed joomap create site map. i found if item in joomap tree menulink (menu alias), cannot work deserved. cause 404 error said component cannot found when menulink clicked. thanks ok, solution. all need modify component code, commenting 1 line problem solved. there no other way. edit : /components/joomap/joomap.html.php and comment line of code, around line number 58, 59 $link .= '&amp;itemid='.$node->id; to //$link .= '&amp;itemid='.$node->id; just comment line , work deserve. hope solve answer. sia

winapi - Creating multiple dialogs in an MFC app with no main Window, they become children of each other -

(title updated) following on this question, have clearer picture what's going on... i have mfc application no main window, exposes api create dialogs. when call of these methods repeatedly, dialogs created parented each other instead of being parented desktop... have no idea why. but anyway after creation, unable change parent null or cwnd::getdesktopwindow()... if call setparent followed getparent, nothing has changed. so apart weird question of why windows magically parenting each dialog last 1 created, there i'm missing able set these windows children of desktop? updated : have found reason this, not solution. dialog constructor, end in: bool cdialog::createindirect(lpcdlgtemplate lpdialogtemplate, cwnd* pparentwnd, void* lpdialoginit, hinstance hinst) { assert(lpdialogtemplate != null); if (pparentwnd == null) pparentwnd = afxgetmainwnd(); m_lpdialoginit = lpdialoginit; return createdlgindirect(lpdialogtemplate, pparentwnd, hi...

ruby - Rails validates_length_of is misbehaving -

i have rails model adding validations , seem have run bit of weirdness 1 of validators. so here table working (from schema.rb): create_table "clients", :force => true |t| t.string "name" t.string "last_contact" t.integer "contacting_agent" t.date "last_payment_date" t.float "last_payment_amt" t.datetime "created_at" t.datetime "updated_at" t.string "office" t.integer "client_id" end i have normal view, with: <%= error_messages_for 'client' %> <h1>new client</h1> <% form_for @client |new| %> <table id='newform'> <tr> <th>field</th> <th>value</th> </tr> <tr> <td> id </td> <td> <%= new.text_field :client_id %> </td> </tr> <tr> <td> name </td> <td...

asp.net mvc 3 - MVC 3 Razor Meta Description / Keywords -

what simplest way of getting meta description / keywords onto _layout page? similar how page title nice. such as <title>@viewbag.title</title> <meta name="keywords" content='@viewbag.keywords'/> <meta name="description" content='@viewbag.description'/> my view like: @{ viewbag.title = "contact me"; viewbag.keywords = "my, keyword, list, etc"; } your view should not responsible of (do not add logic views). instead, it's action method should specify meta information. check answer here: asp.net mvc - strategy including seo information such meta keywords , descriptions the answer still apply, although should use viewbag instead of viewdata .

c# - asp:Validator in invisible elements + invisible targets -

somewhat straightforward: asp:validators still perform validation when they're in invisible containers? how if controltovalidate target invisible? for example: <asp:panel id="mypanel" runat="server" visible="false"> <asp:textbox id="mytextbox" runat="server" /> <asp:requiredfieldvalidator id="myrfv" runat="server" controltovalidate="mytextbox" /> </asp:panel> above validator in invisible panel. myrfv still perform validation? how if mytextbox invisible instead? i'm asking because have specialized validators in aspx, wherein have panels hidden/shown dynamically. while i'm disabling validators themselves, i'm curious whether they'll automatically disable anyway. thanks guys! :d if panel invisible nothing rendered, there no validator. in other case control validate invisible try validate textbox , return false(not valid) defa...

c++ - Isapi filter - state -

i have isapi filer , want add logic based on incoming domain ( server farm hosts many domains). there domain list dynamic , can export these domain list text file , read isapi , there way keep file in memory (is array or linked list) save io call. similar global application state . how worker processes distributed across servers? have 1 server 1 worker process, or multiple servers? if have 1 server 1 worker process, can read file static array or string manage (just make sure account concurrent threads reading/modifying simultaneously) if have multiple worker processes on 1 server, can use named shared memory. i've used before in isapi filters share information, , works pretty well. should take care of concurrency you. can read more here: http://msdn.microsoft.com/en-us/library/aa366551%28v=vs.85%29.aspx if you're spread across multiple servers, use distributed cache memcached. more complex set up, it'll give performance. there's thread on setti...

java - Pseudo-Backwards Builder Pattern? -

in legacy codebase have large class far many fields/responsibilities. imagine pizza object. it has highly granular fields like: haspepperoni hassausage hasbellpeppers i know when these 3 fields true, have supreme pizza. however, class not open extension or change, can't add pizzatype, or issupreme(), etc. folks throughout codebase duplicate same if(a && b && c) issupreme) logic on place. issue comes quite few concepts, i'm looking way deconstruct object many subobjects, e.g. pseudo-backwards builder pattern. pizzatype pizzatype = pizzaunbuilder.buildpizzatype(pizza); //pizzatype.supreme dough dough = pizzaunbuilder.builddough(pizza); is right approach? pattern exist already? how adapter pattern? basically wrapper class has functionality want can go , forth pizza class. menupizza mypizza = new menupizza(pizza); pizzatype pizzatype = mypizza.getpizzatype(); doughtype doughtype = mypizza.getdoughtype(); and provide reverse functio...

php - How to use where condition for the for a selected column using subquery? -

i have 2 columns company , product. i use following query products matching particular string... select id,(select name company product.cid=company.id) company,name,selling_price,mrp product name '$qry_string%' but when need list products of specific company how can do? i tried following in vein select id,(select name company product.cid=company.id) company,name,selling_price,mrp product company '$qry_string%' help me what trying not require subquery, simple join enough. try this: select c.name, p.id, p.name, p.selling_price, p.mrp company c inner join product p on c.id = p.cid c.name '$qry_string%' i think problem query tried cannot use fields result of subquery (in case, "company") in where clause. might try having instead.

java - Is there a difference between ECDH and ECDSA keys? -

i'm building network application uses bouncycastle cryptography provider. let's have generate keypair: ecparameterspec ecspec = ecnamedcurvetable.getparameterspec("prime192v1"); keypairgenerator g = keypairgenerator.getinstance("ecdsa", "bc"); g.initialize(ecspec, new securerandom()); keypair pair = g.generatekeypair(); i'm confused why you're getting instance of ecdsa keypairgenerator. why doesn't ec ? know there's ecdh key type shipped bouncycastle, thought 2 represented same stuff points on curve -- or wrong theory behind it? the reason ask right application uses ecdh fine establish aes secret key, want use same ec key sign each message using ecdsa. ecdsa , ecdh distinct standards (ansi x9.62 , x9.63, respectively), , used in distinct contexts. x9.63 explicitly reuses elements x9.62, including standard representation of public keys (e.g. in x.509 certificates). hence, ecdsa , ecdh key pairs largely interch...

Optimizing Mysql Query For Group by with date functions -

i have report pulls information summary table , ideally pull 2 periods @ once, current period , previous period. table structured thusly: report_table item_id int(11) amount decimal(8,2) day date the primary key item_id, day. table holds 37k records 92 different items , 1200 different days. using mysql 5.1. here select statement: select r.day, sum(r.amount)/(count(distinct r.item_id)*count(r.day)) `current_avg_day`, sum(r2.amount)/(count(distinct r2.item_id)*count(r2.day)) `previous_avg_day` `client_location_item` `cla` inner join `client_location` `cl` inner join `report_item_day` `r` inner join `report_item_day` `r2` (r.item_id = cla.item_id) , (cla.location_id = cl.location_id) , (r.day between from_unixtime(1293840000) , from_unixtime(1296518399)) , (r2.day between from_unixtime(1291161600) , from_unixtime(1293839999)) , (cl.location_code = 'location') group month(r.day); at present query takes 2.2 seconds in environment. explain plan is: ...