Posts

Showing posts from February, 2012

c# - Delete query in Linq -

i have simple code shows error. dont know going wrong. shows error in last line.."deleteonsubmit" linq_testdatacontext db = new linq_testdatacontext(); var remove = aremove in db.logins aremove.username == usernamestring && aremove.password == pwdstring select aremove; db.logins.deleteonsubmit(remove); you missing foreach loop delete entity. use below var remove = aremove in db.logins aremove.username == usernamestring && aremove.password == pwdstring select aremove; and after that foreach (var detail in remove) { db.logins.deleteonsubmit(detail); } and @ last try { db.submitchanges(); } catch (exception e) { // provide exceptions. } hope you.

java - How to turn off VelocityViewResolver errors in Spring? -

i'm using velocity , spring. within spring, i'm using velocityviewresolver paired contentnegotiatingviewresolver . part, works great. problem contentnegotiatingviewresolver queries velocityviewresolver many different content sets (as should). when velocity engine doesn't find particular template, error produced similar following: 2011-02-04 13:37:15,074 error [http-8080-2] velocityengine: resourcemanager : unable find resource 'foo.json.vm' in resource loader. this not ideal. ideally, if template isn't found, warning or similar produced. if template doesn't exist particular content type, don't care... means content type isn't supported through view resolver. any idea on how suppress error though velocityviewresolver , velocityview , or contentnegotiatingviewresolver ? so, found best way add logger statement log config file velocity engine (velocity , project both use commons logging). logger statement looks this: ...

c++ - Operator overload for [] operator -

why need overload [] operator? have never come across practical scenario necessary. can tell me practical use case this. err.. std::vector<t> , std::basic_string<t> , std::map<k, v> , , std::deque<t> ? i used class representing registry key, operator[] returned object representing registry value string between []s. see also, spirit parser framework , uses [] semantic actions.

HTTP digest authentication for AJAX requests -

hey so, i've got api i'm making calls in browser application. said api lives on server requires whitelisting , http digest authentication. to meet whitelisting requirement, i'm running api calls through proxy, whitelisted. calls originating iframe, populated index.html file. what need know how can authenticate via http digest in background. of resources can find online seem involve original http digest authentication setup, i'm looking automate login. despite non-secretive subject matter, somehow critical keep digest parameters obfuscated users. perhaps change served file index.php , somehow set magic headers? then, if calls made via xhr, index.php headers authenticate separate request? overall, i'm lost, , api developers in question not responsive, thought i'd turn here. it appears in end, not possible. had switch building thin back-end route requests through.

vb.net - How can i create a directory in drive C:\? -

i trying create directory in drive c: (at win7 target machine) directory.createdirectory far no luck. i believe problem has permissions-security... here am.. how can create directory in drive c? you should not use root of c ordinary application. if you're using because think it's folder can count on, use appdata or temp instead. if not ordinary application, instead administrative application, put manifest on requesting elevate (requireadministrator) can gain access areas of hard drive , registry protected uac.

Should data be descriptive of itself? In what cases should it preferably be or not be? -

i not sure how put simple question. i going use example. say sending parameter web browser server. javascript know it. setting page element have 4 different values. make 0-3, or make "bright", "dark", "transparent", "none". see mean? in 1 case data descriptive. now step outside of realm of web development. in fact, step away facet of programming not require 1 method or other, , think of prefer 1 on other. meaning beneficial on goals if done in descriptive manner, or beneficial if done in cryptic manner. can think of examples want 1 on other? ps: may need tags on 1 guys. benefit of number variant smaller data size. can useful if communicating lot of data or communicating on restricted bandwidth channel. comparing numbers faster comparing strings. the alternative meaningful names beneficial when need easy extensibility , maintainability. can see value means without using other translation table. can enable others add new va...

syntax - Programming terms - field, member, properties (C#) -

i trying find meaning of terms due language barrier not able understand used for. assume "field" variable (object too?) in class while "property" object returns specific value , cannot contain methods etc. "member" understand object declared on class level. these assumptions based on commented code samples careful programmers used "property region" etc. appreciate if explain me. in c# : fields : these variables declared @ class level. public class someclass { private int someinteger; // field public double somedouble; // field protected stringbuidler stringbuidler; // still field } properties : used accessors private field of class, can provide , set methods wrap logic around field manipulation. public class someclass { private stringbuilder stringbuilder; // property declaration public stringbuilder stringbuilder { { if(this.stringbuilder == null) t...

c# - Sending SMS from Windows Mobile -

this question asked @ many places not find satisfying answer asking in stackoverflow. hope answer soon. i need make windows application (vc++/c#/vb.net) can send sms using windows mobile connected through activesync or device center without gsm modem. hope positive replies :) just we're clear, want use windows mobile application send sms using active sync connection pc rather using wwan cellular modem? if pc connected internet, suppose use activesync connection internet access mobile device. there, access web service allows sending sms messages. verizon provides 1 here: https://text.vzw.com/customer_site/jsp/messaging_lo.jsp this seems silly, though. why not use device's wlan connect internet instead of connecting pc? if must connected pc, why not use pc send sms? -paulh

iPhone:How to create scrollview in a tollbar which is placed under(below) navigation bar? -

how create scrollview in toolbar under(just below) navigation bar, same shown in image available there in below http link. please see image located in below link, , scrollview created(tabs "video, us, world" etc.) under "my title" navigation bar. guide me how can add scrollview in toolbar under navigation bar? thank you. image link: http://www.freeimagehosting.net/image.php?89c222772d.png

c# - What's the difference between a class listener and an instance listner in WPF? -

i trying wrap head around wpf specific stuff, , have yet find concrete relation between uielement.addhandler method , eventmanager.registerclasshandler method. i have googled bit , found interesting msdn article: http://msdn.microsoft.com/en-us/library/ms747183.aspx here states: "routed events consider 2 different types of listeners event: class listeners , instance listeners. class listeners exist because types have called particular eventmanager api, registerclasshandler, in static constructor, or have overridden class handler virtual method element base class. instance listeners particular class instances/elements 1 or more handlers have been attached routed event call addhandler." alright know difference between class , instance, somehow cannot make sense out of specific part of document. can clear me? i don't know, want know. things pretty simple: can register handler @ instance (object) level, or @ class level. the difference is, when regi...

Convert old 3d model in DWB format? -

i've got old 3d models in ".dwb" file format. application created them called designer's workbench coryphaeus software. think company long gone. goal somehow convert models format can imported google sketchup can use them in google earth. ideas? help! amb my first approach find else read files , export them that. assuming can't need follow following procedure (reverse engineering): get very simple model (a 1x1x1 cube centred on known point, not 0,0,0) in dwb format. open file in hex editor , examine find cube. work out codes mean position, size etc. repeat other models (cylinder, line, etc.) when you've done enough files, run models want import through process , see comes out. resemble input? if not repeat process tweaking code until does. i'm sorry can't more specific, need file format.

jQuery: submit a form when the checkbox is selected -

i have form, , want automatically update when click on checkbox. current code: $('.option img').click(function() { $("#views-exposed-form-portfolio-page-1").submit(); }); however, selected checkbox not stored before form submitted, , selection has not effect. thanks $("#mycheckbox").change( function(){ $("#views-exposed-form-portfolio-page-1").submit(); } ); you can check , see if checkbox checked before submitting form, way easier submitting based on click event (which fires before change event, seems).

Send a SQL server email every 1 hour -

i have following sends email recipients table in database. im trying send email every hour. how that? this have right now? declare @recipient varchar(4000) use data select @recipient = stuff((select ';' + email dbo.email xml path('') ), 1, 1, '') exec msdb.dbo.sp_send_dbmail @profile_name='sql server alerts system', @recipients = @recipient, @subject='test message', @body='this body of test message. congrates database mail received successfully.' create scheduled sql server agent job

c++ - Problem when converting char* to string -

when convert char* string gives bad memory allocation error in 'new.cpp' . used following method convert char* called 'strdata' , 'strorg' string. const char* strdata = dt.data(); int length2 = dt.length(); string s1(strdata); first time work without problem. in second convertion gives above error. when swap 2 conversion in order, give error in second conversion regardless of char* converting. whole code shown in following. mysqlpp::query query = conn.query("select data,origin image id =2"); mysqlpp::usequeryresult res = query.use(); mysqlpp::row eee= res.fetch_row(); mysqlpp::row::reference dt = eee.at(0); mysqlpp::row::reference org = eee.at(1); const char* strdata = dt.data(); int length2 = dt.length(); string s1(strdata); istringstream is1(s1); char * imgdata = new char; is1.read(reinterpret_cast<char *> (imgdata), length2); delete [] strdata; const char* strorg = org...

google play - Android HttpURLConnection cannot redirect to "market://details?id=my.package.name" -

i launching httpurlconnection android device points server i.e. http://example.com/download-app . server receives request , issues redirect market://details?id=my.package.name . aim have android market app on phone open , navigate app download page. however, doesn't seem work. set redirects true on httpurlconnection i.e. httpurlconnection.setfollowredirects(true); but url receive same url server i.e. http://example.com/download-app . if use redirect link using "http" protocol http://market.android.com/details?id=my.package.name , works instead opens new web based market not app on phone. has else experienced this? the aim have android market app on phone open , navigate app download page. then why using httpurlconnection ? if want view web page, use action_view intent : startactivity(new intent(intent.action_view, uri.parse("http://example.com/download-app")));

objectinputstream - java initializing variable for stream in/out -

i have problem below code. not clear how can initialize variables of in/out. during creation of object program hangs when in constructor. hangs @ line of this.inobjects = new objectin......... . create in/out objects once read , write on input/output, strings , objects calling them in methods , applying read write etc etc where going wrong? possible not receiving data hangs? shouldn't, right? public class pokerclient { private pokerclientgui gui; private socket clientsocket; private datainputstream in; private dataoutputstream output; private objectinputstream inobjects; private objectoutputstream outobjects; private hand hand; //constructor public pokerclient() { try { this.gui= gui; this.clientsocket = new socket("localhost", 4444); this.in = new datainputstream(this.clientsocket.getinputstream()); this.inobjects = new objectinputstream(this.clientsock...

c# - Do I need a single instance of the Unity container? -

sorry noob question. i'm beginning use unity 2.0 container silverlight , putting singletons in it. singletons work, need have 1 instance of container in application? assume making new unity container instance whenever want singletons result in separate containers separate singletons. thanks, -jon you need single instance of container achieve singleton behaviour. need register singleton classes containercontrolledlifetimemanager.

Database testing in python, postgresql -

how unit test python dal using postgresql. in sqlite create in-memory database every test cannot done postgresql. i want library used setup database , clean once test done. i using sqlalchemy orm. you can use nose write tests, use sqlalchemy create , clean test database in setup/teardown methods.

clean html a string by element id using php -

as can see subject looking tool cleaning html string in php using html id property, example: according following php string wish clean html erasing black11 $test = ' <div id="block1"> <div id="block11">hello1 <span>more html here...</span></div> <div id="block12">hello2 <span>more html here...</span></div> </div> <div id="block2"></div> '; will became $test = ' <div id="block1"> <div id="block12">hello2 <span>more html here...</span></div> </div> <div id="block2"></div> '; i tried tool htmlpurifier.org , can't desirable result. thing achieved removing elements tag; erasing id; erasing class. is there simple way achieve using purifier or other? thanks in advance, as general solution manipulating html data, recommend : loading dom documen...

c# - Sorting DataTable string column, but with null/empty at the bottom -

i need sort datatable or datagridview column string value, null/empty values @ bottom when sorting ascending. the datatable not populated sql statement, no order by. if do datagridview1.sort(new rowcomparer(system.componentmodel.listsortdirection.ascending)) then throws exception, saying datagridview databound, correct, doesn't me, , want keep databound. it's .net 2.0, means no linq available! in cases if have column in table: select completed, completed null isnull table order isnull desc, completed desc edit: in vb.net each srsearchresult in srcsearchresultcollection try dr = dt.newrow() dr("cn") = srsearchresult.getdirectoryentry().properties("cn").value dr("account") = srsearchresult.getdirectoryentry().properties("samaccountname").value dr("nachname") = srsearchresult.getdirectoryentry().properties("sn...

java - overloading with both widening and boxing -

public void add(long... x){} public void add(integer... x){} add(2); this produces error...why overlaoding not performed both widening , boxing? but overloading without vararg works fine public void add(long x){} public void add(integer x){} add(2); here add(long x) executed widening beats boxing...why not same concept var arguments java compiler performs 3 attempts choose appropriate method overload ( jls §15.12.2.1 ): phase 1: identify matching arity methods applicable subtyping (possible boxing conversions , methods varargs ignored) phase 2: identify matching arity methods applicable method invocation conversion (takes boxing conversion in account, ignores methods varargs) phase 3: identify applicable variable arity methods (examines possibilities) so, examples works follows: without varargs: add(long x) identified applicable method on 1st phase (this method applicable subtyping since int subtype of long , §jls 4.10.1 ), following phas...

setup settings send to its parent class in ruby -

how can write (child) class so: class child < parent create_columns :name, :address end that: class parent # can access create_columns set child class? end thanks. you can solve using inherited hook method in ruby, can track children. class parent self.inherited(base) self.children << base end end class child < parent def initialize @@instances << self end def self.instances @@instances end now can things parent.children.each { |child| child.instances.collect(:&name) }. if name accessable :-) hope helps!

java - "Non-static method cannot be referenced from a static context" error -

this question has answer here: non-static variable cannot referenced static context 11 answers i have class named media has method named setloanitem : public void setloanitem(string loan) { this.onloan = loan; } i trying call method class named gui in following way: public void loanitem() { media.setloanitem("yes"); } but getting error non-static method setloanitem(java.lang.string) cannot referenced static context i trying change variable onloan in media class "yes" gui class. i have looked @ other topics same error message nothing clicking! instance methods need called instance. setloanitem method instance method (it doesn't have modifier static ), needs in order function (because setting value on instance it's called on ( this )). need create instance of class before can call method on it: medi...

java - OutOfMemory Exception - how does VisualVM help locate the memory leak with heapdump file? -

i've been testing webapp locally on pc , monitoring visualvm. started using jmeter, suggested should load testing since suspected have slow memory leak somewhere. today webapp threw outofmemory exception. had heapdumponoutofmemoryerror , heapdumppath params set in case ever happened. heap dump file generated. i opened file (java_pid2760.hprof) in visualvm, , honestly, don't understand how i'm supposed able pinpoint culprit of memory leak... how use visualvm analyze heap dump , find class/instance generating memory leak? here's couple of links found helpful when debugging memory leaks: http://olex.openlogic.com/wazi/2009/how-to-fix-memory-leaks-in-java/ http://www.ibm.com/developerworks/rational/library/05/0816_guptapalanki/ edit: you might want try: http://rejeev.blogspot.com/2009/04/analyzing-memory-leak-in-java.html

continuous integration - How to make teamcity's svn checkout more verbose? -

we have large svn external containing 30,000 500k files. checkout can take long time , see progress in teamcity logs happens. is there way use more verbose logging when doing svn checkout just.... [19:26:00]: updating sources: agent side checkout... [19:26:00]: [updating sources: agent side checkout...] perform clean checkout. reason: checkout directory empty or doesn't exist [19:26:00]: [updating sources: agent side checkout...] cleaning /opt/teamcity/buildagent/work/937995fe3d15f1e7 [19:26:00]: [updating sources: agent side checkout...] vcs root: guru 6 trunk externals [19:26:00]: [vcs root: guru 6 trunk externals] revision: 6521_2010/04/27 19:25:58-0500 i'm afraid there no way make agent-side checkout more verbose. if you'd use server-side checkout, checkout progress visible, because teamcity tracks data sent server build agent , shows how data have been transferred. please feel free post feature request teamcity tracker @ ht...

.net - Building a chained set of method calls from a C# object in f# -

i'm learning f# , got thinking. can chain operations normal operators, such let achainedfunc = list.map func >> list.reduce func then later can go let result = achainedfunc alist results of same operations, allowing nice reuse in short amount of code. but, if have c# object want invoke methods object, pre-build chain f# example above? obviously requires object can normal a.method1().method2().method3() make work, there way sanely set allow work without building method pass in instead? if wanted create sequence of static method calls (or extension method calls), sometype.method1 , sometype.method2 , othertype.method3 , can write c# method compose behaves >> operator in c#: func<t, r> compose<t, u, r>(func<t, u> f1, func<u, r> f2) { return v => f2(f2(v)); } then should able write like: compose(sometype.method1, sometype.method2).compose(othertype.method3); // ... note work methods taking single argument (but ...

bash - Copy/publish images linked from the html files to another server and update the HTML files referencing them -

i publishing content drupal cms static html pages on domain, hosted on second server. building html files simple (using php/mysql write files). i have list of images referenced in html, of exist below /userfiles/ directory. cat *.html | grep -oe [^\'\"]+userfiles[\/.*]*/[^\'\"] | sort | uniq which produces list of files http://my.server.com/userfiles/another%20user1.jpg http://my.server.com/userfiles/image/image%201.jpg ... my next step copy these images across second server , translate tags in html files. i understand sed tool need. e.g.: sed 's/[^"]\+userfiles[\/image]\?\/\([^"]\+\)/\/images\/\1/g' should change http://my.server.com/userfiles/another%20user1.jpg /images/another%20user1.jpg , cannot work out how use script. i.e. can use update files in place or need juggle temporary files, etc. how can ensure files moved correct location on second server it's possible use sed change file in-place using -i option...

windows - Produce video from OpenGL C program -

i have c program runs scientific simulation , displays visualisation in opengl window. want make visualisation video, go on youtube. question: what's best way make video c / opengl program? the way i've done in past use screen capture program, labour-intensive (have start/stop screen capture program, save video file, etc...). seems there should way automate process of making video within c program. can leave running overnight , have 20 videos through in morning, , choose best 1 put on youtube. youtube recommend "mpeg4 (divx, xvid) format @ 640x480 resolution". i'm using glut 3.7.6_3, if makes difference. can change windowing system if there's reason. i'm running windows (xp), prefer answers work on windows, linux answers ok too. can use linux if it's not possible video stuff on windows. have friend makes .png image each frame of video , stitches them using "mencoder" on linux. you can use glreadpixels function (see e...

visual c++ - OpenMP implementations in VC++ 2008, 2010 -

depending on implementation, omp can quite useful parallelize arbitrary bits of code - e.g parallel section inside method calls 2 independent methods - or can bad. depends on how threads created/cached, think. how vc++ 2008 implementation work? , 2010 implementation different in terms of features , performance/flexibility? the openmp implementation in both vs2008 , vs2010 compliant version 2.0 specification. there annotations in msdn library doesn't go deep. best place detailed specifications @ openmp.org site .

c# - Set both Text and Value property of ComboBox in design time -

i need add following items combo box. value displaytext mpost posted call calling rscan re-scan these items static, , not retrieved database... hence thought of assigning these in design time itself. i'm unable use items property asks 1 value per item... please help. ps : in case suggesting bindingsource, please give me example. not able find one. you use bindinglist<keyvaluepair<string, string>> : var items = new bindinglist<keyvaluepair<string, string>>(); items.add(new keyvaluepair<string, string>("mpost", "posted")); items.add(new keyvaluepair<string, string>("call", "calling")); items.add(new keyvaluepair<string, string>("rscan", "re-scan")); mycombobox.datasource = items; mycombobox.valuemember = "key"; mycombobox.displaymember = "value"; i don't think you're going find solution sim...

iphone - For a manual speedometer control, how do I convert needle angle to speed? -

Image
i'd have manual speedometer control user can drag needle particular speed setting, following: from angle of above needle, how read speed corresponds to? example, above read speed of 100. i've done calculation myself (but in reverse, given speed, adjust needle angle) on similar app. presumably code knows angle of needle since you're animating it, , prevent needle going below 0 or above 160. i'll assume needle image @ rest pointing straight , down (at 80mph) figure out angle when needle pointing @ 160mph, , pointing @ 0mph putting nslog dumping out angle when animate in response touches , notice values make needle displaying 0 , 160 (you can tweak in code later right). i'm assuming positive angles rotate clockwise , negative angles rotate counter-clockwise. then speed arbitrary angle is: double mphperdegree = 160 / (angle160mph - angle0mph); double speed = (currentangleindegrees * mphperdegree) + 80.0;

c# - ...may not be used in this context...while serialization -

i've webservice , webmethod [webmethod] [xmlinclude(typeof(contractcar[])) public object getobjects(cars[] cars) { return translator.toobjects(facade.getobjects(cars); } public static object getobjects(cars cars) { list<car> cars =new list<country(...fillingcollection) return cars.toarray(), } public static object toobjects(object collection) { if(collection car[]) { return convertmodelcarstocontractcars(collection), } public contractcar[] convertmodelcarstocontractcars(cars[] collection) { ...there rewriting pool... } and exception @ side of client: there error generating xml document. i'm using function check collection send client , works. public static void serializecontainer(object obj) { try { // make sure construsctor runs inside // try-catch block xmlserializer ser = new xmlserializer(typeof(object)); textwriter w = new streamwriter(@"c:\li...

android - RemoteViews addView function returns errors on AppWidget -

i'm trying create appwidget displays number of items (which can change). i'd generate textviews dynamically, assume using: remoteviews updateviews = new remoteviews(context.getpackagename(), r.id.widgetmain); remoteviews newview = new remoteviews(context.getpackagename(), r.id.widgetitem); updateviews.addview(0, newview); but returns problem loading widget error. widgetitem.xml textview within linearlayout. widgetmain.xml 2 textviews within linearlayout. what doing wrong? updateviews.addview( 0 , newview); you should specify correct viewid rather 0 parent of widgetitem. exmaple, can add empty container under widgetmain purpose.

Is there anyway to load up a asp.net page object and render its contents to string from a console application? -

i trying use aspx pages email templates. there bunch of objects on page used replacements in html. because it's aspx page i'll able use databinding, repeaters, etc. @ run time, want able instantiate aspx page path, pass in bunch of properties, , rendered result of page , email it. seems pretty straightforward asp.net website (maybe using buildmanager or server.execute.) however, want able use same templates via console application loading page object filepath. possible? you host own webserver. cassini webserver . in own application (a windows-based desktop-cms), include web server, (non-cassini). works well, not serve asp.net plain, html. as did research then, first wanted use cassini, too, @ point, found out user privileges required run successfully; may not issue you, keeping in mind , try run permissions of later user, might idea.

cocoa touch - UIToolbar above UIWebView inside UIScrollView -

i'd display toolbar above uiwebview hide toolbar until person "pulls down". the same functionality can seen in safari on iphone. when page loads, toolbar containing address hidden. must pull down. in safari it's possible scroll , see toolbar or scroll down through page contents. i've tried placing uitoolbar , uiwebview inside uiscrollview didn't work. i've tried setting uiscrollview size of toolbar , webview combined, didn't work. - (void)viewdidload{ cgsize size = cgsizemake(webview.frame.size.width, toolbar.frame.size.height + webview.frame.size.height); [scrollview setcontentsize:size]; } how should go doing this? edit anyone looking @ should consider question , accepted answer both old , api might have changed allow this. the uiwebview uiscrollview it's not going work. i'm not sure how apple it, 1 way it, if have control on content of web view, write html , css replicates addres...

python - Distutils - Where Am I going wrong? -

i wanted learn how create python packages, visited http://docs.python.org/distutils/index.html . for exercise i'm using python 2.6.2 on windows xp. i followed along simple example , created small test project: person/ setup.py person/ __init__.py person.py my person.py file simple: class person(object): def __init__(self, name="", age=0): self.name = name self.age = age def sound_off(self): print "%s %d" % (self.name, self.age) and setup.py file is: from distutils.core import setup setup(name='person', version='0.1', packages=['person'], ) i ran python setup.py sdist , created manifest, dist/ , build/. next ran python setup.py install , installed site packages directory. i run python console , can import person module, cannot import person class. >>>import person >>>from person import person traceback (most recent call last)...

tinymce - How to get the Preview image using advImage plugin in Rails application -

hi , using tinymce advimage plugin in rails application. i have doubt when click on insert/edit iamge in tinymce popup window comes , in appearance tab preview not shown how preview image ?? in appearance tab there 2 "previews" in advanced image plugin dialog. first preview of image have selected. second allow visualise style changes make (for instance border, alignment) , uses "sample" image. i assume see selected image displayed instead of "sample" image. achieve this, need alter advimage plugin, bundled tinymce, use selected image instead of default (sample.gif). one thing consider if end user selects large image, wouldn't able see application of style changes within small preview window.

jquery radio button when checked need an alert -

in application need radio group, in whenever button checked, alert occur can post value ajax post in jquery. can me please how can in jquery? try this: $(function(){ $('input[type="radio"]').click(function(){ if ($(this).is(':checked')) { alert($(this).val()); } }); }); if give radio buttons class can replace code $('input[type="radio"]') $('.someclass') .

Generate random number between two numbers in JavaScript -

is there way generate random number in specified range (e.g. 1 6: 1, 2, 3, 4, 5, or 6) in javascript? if wanted between 1 , 6, calculate: math.floor(math.random() * 6) + 1 where: 1 start number 6 number of possible results (1 + start (6) - end (1) )

c# - Sending a Tuple object over WCF? -

is system.tuple class supported wcf's data contract serializer (i.e., can pass tuple objects wcf calls and/or receive them part or of result)? i found this page , not clear, definitive "you can send , receive tuples wcf" answer hoping for. i'm guessing can, long of types within tuple supported data contract serializer -- can provide me more definitive answer? thanks. the tuple types marked serializableattribute , therefore, if types store within serializable, should able serialized wcf well. check out: links of tuple'1 , tuple'2 , etc. says: [serializableattribute] public class tuple<t1> : istructuralequatable, istructuralcomparable, icomparable, ituple note document linked contains following line: the [serializable] / iserializable programming model not supported in partial trust environment. so, may not easy seem. (btw, tuple static class worth checking out.)

javascript - WP Plugins - SEO Smart Links messes with my plugin -

i have client has set seo smart links plugin mine. seo smart links replace text links sees fit. problem replaces text inside < script > tag seo smart links disabled (good): var fv1='zi4qkqp1dag;eugial2onxa;ukxgdkkrmjq;ejld6hhbk90'; var fv2='youtube;youtube;youtube;youtube'; var fv3=''; var fv4='09 02 2011;25 september 1957;26 mei 1957;26 maart 2008'; var fv5='nederland 3 vs 1 oostenrijk alle doelpunten nederlan 3 vs 1 oostenrijk 9 feb. 2011 sneijder 28 huntelaar 48 kuyt 70 arnautovic 84; nederland vs oostenrijk 1 1, 25 september 1957; oostenrijk vs nederland 3 2, 26 mei 1957; samenvatting oostenrijk vs nederland (26 03 2008) 3 vs 4'; var width = 600; var height =400; var flashvars = { totalwidth:width, totalheight:height, autoplay:"off", autoplaynextvideo:"on", menuposition:"down", video:fv1, types:fv2, ...

request - Rhino - Convert Parameter Map to Native JS object -

what's "right" way convert parameters request native js object? it seems no matter do, end java object. primitivewrapfactory i'm looking for, easiest way call: string(javaobj), since want them strings.

using focus function with jquery live -

i have page in can use jquery focus function using live... $(".comment_text_class").live('focus', function() { //do something... }); but when comes page(ajax loading) focus function doesn't work as should using live function... as suggested used focusin function.. $(".comment_text_class").live('focusin', function() { //do something... }); but still new elements not have behavior... also want hide using live function doesn't work @ all.. even elements in page itself... $(".comment_button").live('hide', function(){}); is focus , hide function implemented @ jquery 1.4.2 or bug... because live focus not working jquery 1.4 version... well page here... http://pradyut.dyndns.org/webapplicationsecurity/newuser.jsp?id=2 sorry .. fixed out... please help... thanks pradyut india .live() doesn't work think believe. doesn't watch new elements , execute code, rather waits or ...

c# - Text reformatter gradually slows with each iteration -

edit 2 okay, i've posted copy of source @ gist.github , have 1 lingering problem can't resolve. findline() returns -1. i've narrowed cause down if statement, can't figure out why. know symbol , symbollist both getting passed data. /edit 2 i have simple c# program looks .csv file, reads text in file, reformats (and includes information sql query loaded datatable), , saves .tsv file later use program. my problem source .csv file on 10,000 lines , program slows gradually iterates through lines. if .csv file ~500 lines takes 45 seconds complete, , time exponentially worse .csv file gets larger. the sql query returns 37,000+ lines, requested once , sorted same way .csv file is, won't notice running through file unless can't find corresponding data, in case makes way through , returns appropriate error text. i'm 99% sure it's not cause of slowdown. the y , z loops need long are. if it's absolutely necessary can scrub data initial ...

.net - Reference platform specific System.Data.SQLite -

i using sqlite unit testing , might use database local development/staging. the system.data.sqlite has 2 versions: x86 , x64. correct 1 should used specific platform. i have 64 bit win7, other guys in team might use 32-bit oss. server's platform not known @ stage. if use 32-bit version of assembly on 64-bit platform badimageformatexception: not load file or assembly 'system.data.sqlite' . believe similar happen trying use 64-bit assembly on 32-bit platform. so question best way reference sqlite assembly not depend on platform , people can use it? it ok use 32-bit version of assembly on 64-bit platform (maybe there switch somewhere?). if it's installed gac, reference assembly , system pick correct one. otherwise, need make sure reference correct 1 "manually" (i have, in past, used build system copied correct version "deploy" folder when building. these days, 64-bit it's not such big deal). alternatively, can build appli...

php - When sending headers to download a PDF, Safari appends .html -

here request , response headers http://www.example.com/get/pdf /~get/pdf http/1.1 host: www.example.com user-agent: mozilla/5.0 (macintosh; u; intel mac os x 10.6; en-us; rv:1.9.2.3) gecko/20100401 firefox/3.6.3 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: http://www.example.com cookie: etc http/1.1 200 ok date: thu, 29 apr 2010 02:20:43 gmt server: apache/2.2.14 (unix) mod_ssl/2.2.14 openssl/0.9.8i dav/2 mod_auth_passthrough/2.1 mod_bwlimited/1.4 frontpage/5.0.2.2635 x-powered-by: me expires: thu, 19 nov 1981 08:52:00 gmt pragma: no-cache cache-control: private content-disposition: attachment; filename="file #1.pdf" content-length: 18776 keep-alive: timeout=5, max=100 connection: keep-alive content-type: text/html; charset=utf-8 ---------------------------------------------------------...

How do I get the sum of all numbers in a range function in Python? -

i can't figure out how take x (from code below) , add sum , divide number of ratings. example given in class 4 ratings, numbers being 3,4,1,and 2. average rating should 2.5, can't seem right! number_of_ratings = eval(input("enter number of difficulty ratings positive integer: ")) # number of difficulty ratings in range(number_of_ratings): # each diffuculty rating x = eval(input("enter difficulty rating positive integer: ")) # next difficulty rating average = x/number_of_ratings print("the average diffuculty rating is: ", average) your code doesn't add anything, overwrites x in each iteration. adding variable can done += operator. also, don't use eval : number_of_ratings = int(input("enter number of difficulty ratings positive integer: ")) x = 0 in range(number_of_ratings): x += int(input("enter difficulty rating positive integer: ")) average = x/number_of_ratings print("t...

Issue on passing a checkbox set to an AppEngine script through jQuery Ajax/Json -

i have set of checkboxes multiple choice allowed. parse set way: if ($("input[name='route_day']:checked").length > 0) { $("input[name='route_day']:checked").each(function(){ if(this.value != null) route_days_hook.push(this.value); }); datatrap.route_days = $.json.encode(route_days_hook); } ...and pull whole datatrap appengine python script via jquery ajax. however, python script bugs. if change datatrap.route_days value string instead of json encoded object, works fine. question is: how can pass checkbox set script using ajax , still able iterate on over script? have tried: datatrap.route_days = $.parsejson(route_days_hook); edit if didn't work, maybe it's because trying convert array object json... try solution instead.

programming languages - In PHP, if a variable does not have a value, why does isset() still return TRUE? -

here code: <?php $ja = ''; if(isset($ja)) echo "cool!"; ?> i "cool!" when running simple piece of code in browser. learned php.net isset — determine if variable set , not null well, in code, did declare variable $ja, didn't add value it, shouldn't "null"? even though '' seems nothing, still has value (a null character @ end of string). isset() checks if variable set or not, in case (to ''), is. may want set $ja null first beforehand, instead of setting empty string... or use empty() ;)

php - Known problems with filemtime() on Windows - files getting touched arbitrarily? -

is there known issue leading file modification times of cache files on windows xp sp 3 getting arbitrarily updated, without actual change? is there service on standard windows xp - backup, sync, versioning, virus scanner - known touch files? have .txt extension. if there isn't, forget it. i'm getting wrong in cache routines, , i'll debug way through. background: i'm building simple caching wrapper around slow web site on windows server. i comparing filemtime() time stamp columns in data base determine whether cached file stale. i'm having problems using method because modification time of cache files seems updated in between operations without me doing anything . results in stale files being displayed. i'm user on machine. operating system windows xp, webserver xampp apache 2 php 5.2 you setup logging * on machine find out changing files. description take happens frequently, might find processmonitor ( german ) better solution moni...

error message with scala installation -

i install scala 2.8.1. used steps http://www.scala-lang.org/node/310 when write 'scala' in command prompt have following error 'java' not recognized internal or external command operable program or batch file do know whats going wrong? as error message pointing out, java missing. have install jre or jdk , make scala find it, example setting java_home jre/jdk. have fun scala

parsing - C# Convert String Decimal to Int -

i have string "246246.246" i'd pass iconvertable interface, toint16, toint32, toin64. best way parse string decimal places integer? this solution, there better solution? string value = "34690.42724"; convert.toint64(convert.todouble(value)); to discounting rounding do: convert.toint64(math.floor(convert.todouble(value))); if need round replace math.floor math.round . edit: since mentioned in comment you'll rounding: convert.toint64(math.round(convert.todouble(value))); if have worry localization/globalization @xls said should apply cultureinfo in conversions. edit 2: alternative method using string function (not terribly elegant imo - maybe elegantized predicate function): convert.toint64(value.substring(0, value.indexof('.') > 0 ? value.indexof('.') : value.length));

How can I make image_crop with the Galleria jQuery plugin different if the image is wider vs taller? -

essentially want change variable image crop depending on dimensions of each image in gallery. if image's height greater width want switch height crop, else keep width crop. using galleria plugin far have code: if ($(image).width() > $(image).height()){ var upordown = "width" } else { var upordown = "height" } an variable here , part of list of options galleria: image_crop : upordown, any appreciated. are looking way fit image inside container, without cropping? try set image_crop (or imagecrop in latest version) false . edit: can listen loadfinish event , set options according image dimensions on fly. need call refreshimage apply changes. $('#galleria').galleria({ extend: function() { var gallery = this, landscape; this.bind('loadfinish', function(e) { landscape = e.imagetarget.width >= e.imagetarget.height ? 'width' : 'height...

c# - Reflection and Generics get value of property -

i trying implement generic method allows output csv file public static void writetocsv<t>(list<t> list) t : new() { const string attachment = "attachment; filename=personlist.csv"; httpcontext.current.response.clear(); httpcontext.current.response.clearheaders(); httpcontext.current.response.clearcontent(); httpcontext.current.response.addheader("content-disposition", attachment); httpcontext.current.response.contenttype = "text/csv"; httpcontext.current.response.addheader("pragma", "public"); bool isfirstrow = true; foreach (t item in list) { //get public properties propertyinfo[] propertyinfo = item.gettype().getproperties(); while (isfirstrow) { writecolumnname(propertyinfo); isfirstrow = false; } ...

SQL 2000 Not Supported by .NET Framework Data Provider for SQL Server in VS2010's Server Explorer Data Connections -

just tried creating data connection sql 2000 database in vs2010's server explorer using .net framework data provider sql server (versus ole) , found didn't work. vs2010 complained had use sql server 2005 , up. this used work in vs2008 (using .net framework data provider sql server instead of .net framework data provider ole db). is vs2010 restriction or has ability connect sql 2000 .net framework data provider sql server been obsoleted in post-2.0 version of .net being used vs2010? anyone know why done ms (please don't speculate - can myself ;>)? according jim lewis microsoft visual web developer team (via this post ) vs2010 dropped support sql2000. to quote post: visual studio 2010 dropped support sql server 2000. you'll either have go vs2008/sl3, upgrade sql server, or things manually outside of visual studio.

Java JSpinner Looks Ugly -

gui i trying use jspinner can see attached image looks bad. i on windows 7. wondering if knows how make good? just clarity. bad means edges dont line , means spin control edges line correctly. thank you. edit: maybe there no cure this? because checked site , examples this! you can try different & feel, although looks right going platform , feel. alternatives (that won't, far know, mimic windows 7 @ feel) substance , nimbus .

Kohana - Facebook app URL -

i'm developing first facebook app on kohana 2.3.x @ moment , noticed usual app url should this: http://apps.facebook.com/ {my_app}/{controller}/{method} but in app shows real url. http://mydomain.com/ {controller}/{method} any idea how fix in kohana? thanks in advance! try changing in application/config/config.php : $config['site_domain'] = 'apps.facebook.com/my_app/';

php - Define data members within constructor -

i have got little snippet of code, want able define each array element new data member. class core_user { protected $data_members = array( 'id' => '%d', 'email' => '"%s"', 'password' => '"%s"', 'title' => '"%s"', 'first_name' => '"%s"', 'last_name' => '"%s"', 'time_added' => '%d' , 'time_modified' => '%d' , ); function __construct($id = 0, $data = null) { foreach($this->data_members $member){ //protected new data member } } //protected new data member you won't able create non-public property @ runtime. if protected paramount, can declare protected array or object , i...

How to amend several commits in Git to change author -

i have made series of commits in git , realise forgot set user name , user email properties correctly (new machine). have not yet pushed these commits repository, how can correct these commits before (only 3 latest commits on master branch)? i have been looking @ git reset , git commit -c <id> --reset-author , don't think i'm on right track. rebase/amend seems inefficient, when have power of filter-branch @ fingertips: git filter-branch --env-filter 'if [ "$git_author_email" = "incorrect@email" ]; git_author_email=correct@email; git_author_name="correct name"; git_committer_email=$git_author_email; git_committer_name="$git_author_name"; fi' -- --all (split across lines clarity, not necessary) be sure inspect result when you're done, make sure didn't change didn't mean to!

c# - Display text on window media player or monitor -

i display text company name on window media player. use drawstring function on form onpaint event covered window media player. use label control display square block on player control set color transparent. develop ktv system has 2 monitor 1 has form controls , has player. please advice me how should do. if talking windows built-in media player going have down , dirty win32 api's, windows hooks, hwnd, etc. can't paint control on window. talking low level windows coding. take @ spy++ ( http://msdn.microsoft.com/en-us/magazine/cc163617.aspx ). it's tool microsoft let's delve details of running application. has component called managedspylib wraps c++ windows libraries in managed library make windows hooks calls easier. ready learn more os ever wanted know. :-)

algorithm - Given an array A,compute B s.t B[i] stores the nearest element to the left of A[i] which is smaller than A[i] -

given array a[1..n] , want compute array b[1..n] such b[i] stores nearest element left of a[i] smaller a[i] . time complexity should o(n) . (for i>1 ,if there no such smaller elements left, b[i] contains a[i] , , b[1]=a[1] .) example : input : 6,9,12,17,11 output:6,6, 9, 12, 9 i thinking implementing stack, put a[1] in b[1] , push stack. filling b[i] ,compare a[i] elements of stack , pop till smaller element. push a[i] stack. is above approach correct, , there cheaper solution? your stack approach correct. works because if pop element bigger a[i] , element never needed elements following a[i] , because can use a[i] instead. each element accessed twice, o(n) .

.net - Instantiating types: when using new? -

i have type mapping class in f# follows: type myclass = val myval: integer new () = { myval = 0; } member self.myval () = self.myval well, want create instance of class. can so: let myinstance = myclass () or let myinstance = new myclass () what's difference? can both? for types implements idisposable should instantiated using new. otherwise following compilation warning. it recommended objects support idisposable interface created using 'new type(args)' rather 'type(args)' indicate resources may owned generated value

php - Zend Framework, getParams -> setParams -

i'm new zend framework didn't find solution yet. problem next: have form, when submitted user goes index controller , there add action. know how can params, want do: $clear = $this->getrequest()->getparams(); foreach ($clear $key => $value) { $clear[$key]=trim(strip_tags($value)); } $this->setrequest()->setparams($clear);//error, argument 1 passed zend_controller_action::setrequest() must instance of zend_controller_request_abstract so question how change in whole page params, if want anywhere access data sure safe. , possible change params index controller. in advance! change setrequest() getrequest(). $this->getrequest()->setparams($clear);

c# - PagedList error when passing Data with Viewmodel -

hi wondering if con shed light problem i´m experiencing when implementing pagedlist code (https://github.com/troygoode/pagedlist) in asp.net mvc3 website. details of i´m trying do: i created viemodel details: public class productviewmodellist { public list<product> productbrowse { get; set; } public int numberofproducts { get; set; } public list<category> categorymodel { get; set; } } then controller holding information want pass view: public actionresult list(int categoryid, int? page) { const int defaultpagesize = 20; int currentpageindex = page.hasvalue ? page.value - 1 : 0; var categorymodel = db.category.include("product").single(c => c.categoryid == categoryid); var paginatedmodel = categorymodel.product.topagedlist(currentpageindex, defaultpagesize); var viewmodel = new productviewmodellist { productbrowse = paginatedmodel.tolist(), numberofproducts = categorymodel.product.count() }; r...

Large numbers to string in JavaScript -

when following: alert((2053716830872415770228778006271971120334843128349550587141047275840274143041).tostring()); i "2.053716830872415e+75" exponential notation. want alert number is. tried tofixed(), toprecision() , tolocalestring() , output same thing. how can accomplish this? note: number variable, cannot alert("208.."); javascript uses 64-bit floating point numbers . impossible precisely store value in javascript number. instead, should use biginteger library. http://www.leemon.com/crypto/bigint.html http://www-cs-students.stanford.edu/~tjw/jsbn/ https://github.com/jtobey/javascript-bignum

iphone - Get UIWebView to scroll and bounce horizontally but not vertically -

i have iphone uiwebview contents approx 1000px x 200px. when scrolling finger, it'll bounce vertically not horizontally. i want opposite: bounce horizontally not vertically. is there trickery need in html achieve this? eg setting width , height on body explicitly maybe? or setting of uiwebview? can following totally disable bouncing, there similar set bouncing on per-direction basis? [[[webview subviews] lastobject] setbounces:no]; thanks lot help in ios 5, don't need access subviews. uiwebview contains scrollview property nested uiscrollview: to disable bounce: webview.scrollview.bounces = no; to bounce vertically: webview.scrollview.alwaysbouncevertical = no; webview.scrollview.alwaysbouncehorizontal = yes;

debugging - php debuggers which are not bloated -

any suggestions php debuggers, not bloated? i tried using xdebug dbgp plugin on notepad++, seems dbgp plugin isn't compatible notepad++ , hence, didn't work out crashing app every time accessed debugger. other suggestions? not sure qualify "not-bloated", i'm using eclipse pdt (along xdebug) , , it's working well. i know colleagues use netbeans, , satisfied (tried mysql couple of times, didn't feel bad) . maybe bit heavy, yes... full ide, under active development, maintained, ... so, not bad choice, imho.

Tapestry class loader with Tomcat and maven -

possible integrate tapestry class loading under tomcat7 , eclipce, if so, how? interesting in making java development alot faster. project consists of: spring mvc+jsp maven string security mysql hibernate log4j tomcat7 eclipse helios extjs i looking stuation can save java file , refresh browser seeing results/changes. (like jrebel). thanks someone on mailing list says it's possible, haven't gotten work 100%. need figure out how point tomcat various locations find resources , not copy resources , libraries webroot folder. try asking on mailing list more instructions.

css - In IE6 div not taking available height while taking in IE7 and FF? -

in ie6 div not taking available height while taking in ie7 , ff? height not defined on div in ie6 div taking height according content inside div while in ie7 , ff div taking full available height just based on little provided... try: <div style="height:xxpx;"> but glorious if posted code , real question...

validation - Unable to validate for date in Spring MVC -

i using custom editors converting string date. code mentioned below @initbinder public void initbinder(webdatabinder binder) { simpledateformat dateformat = new simpledateformat("yyyy-mm-dd"); dateformat.setlenient(false); binder.registercustomeditor(date.class, new customdateeditor(dateformat, false)); } when entering date in "yyyy-mm-dd" inserting. but when entering blank throws exception nested exception java.lang.illegalargumentexception: not parse date: unparseable date: " " i unable validate same. if give other format not able parse. when instantiate customdateeditor, second parameter, in case, should true. true allows empty values. customdateeditor(springsource)

delphi - How to Create a Simple Dictation Pad in Delphi2009+Vista -

the code not complecated.. private { private declarations } spsharedrecocontext1 : tspsharedrecocontext; fmygrammar : ispeechrecogrammar; procedure spsharedrecocontext1recognition(asender: tobject; streamnumber: integer; streamposition: olevariant; recognitiontype: speechrecognitiontype; const result: ispeechrecoresult); procedure spsharedrecocontext1hypothesis(asender: tobject; streamnumber: integer; streamposition: olevariant; const result: ispeechrecoresult); procedure tform1.formcreate(sender: tobject); begin spsharedrecocontext1 := tspsharedrecocontext.create(self); spsharedrecocontext1.onhypothesis := spsharedrecocontext1hypothesis; spsharedrecocontext1.o...

sql server - Firing trigger for bulk insert -

alter trigger [dbo].[tr_o_salesman_ins] on [dbo].[o_salesman] after insert begin -- set nocount on added prevent result sets -- interfering select statements. set nocount on; -- insert statements trigger here declare @slsman_cd nvarchar(20) declare @slsman_name nvarchar(20) select @slsman_cd = slsman_cd,@slsman_name=slsman_name inserted if not exists(select * o_salesman_user slsman_cd = @slsman_cd) begin insert o_salesman_user(slsman_cd, password, user_cd) values(@slsman_cd, @slsman_cd,@slsman_name ) end end this trigger written table(o_salesman) fetch few columns , insert 1 table(o_salesman_user) . presently bulk data getting inserted o_salesman table through stored procedure, trigger getting fired once , o_salesman_user having 1 record inserted each time whenever stored procedure being executed,i want trigger run after each , every record gets inserted o_salesman such both tables should have same count no...

regex - Remove non-ASCII characters from a string using python / django -

i have string of html stored in database. unfortunately contains characters such ® want replace these characters html equivalent, either in db or using find replace in python / django code. any suggestions on how can this? you can use ascii characters first 128 ones, number of each character ord , strip if it's out of range # -*- coding: utf-8 -*- def strip_non_ascii(string): ''' returns string without non ascii characters''' stripped = (c c in string if 0 < ord(c) < 127) return ''.join(stripped) test = u'éáé123456tgreáé@€' print test print strip_non_ascii(test) result éáé123456tgreáé@€ 123456tgre@ please note @ included because, well, after it's ascii character. if want strip particular subset (like numbers , uppercase , lowercase letters), can limit range looking @ ascii table edited: after reading question again, maybe need escape html code, characters appears correctly once rendered. can...