Posts

Showing posts from January, 2015

c# - Linq join query displayed in MVC view -

i'm trying display linq join query in partial web view. here query within controller: public actionresult inactiveusers() { using (modelcontainer ctn = new modelcontainer()) { datetime duration = datetime.now.adddays(-3); var inactive = usrs in ctn.aspnet_users usrs.lastactivitydate <= duration join o in ctn.groups on usrs.userid equals o.userid select new { usrs.username, usrs.lastactivitydate, o.primaryphonenumber, }; return view(inactive.tolist()); } } what i'm bit confused on next. i'm familiar adding typed views using models, happens in case have join query? if point

c# - linq to sql Distinct and orderby -

var result = table1.join(table2, o => o.programid, t => t.programid, (o, t) => new { o.programid, t.program }) .orderby(t => t.program) .distinct(); the above linq statement returns correct result, sql generated (below) not simple be select [t2].[programid], [t2].[program] ( select distinct [t0].[programid], [t1].[program] [table1] [t0] inner join [table2] [t1] on [t0].[programid] = [t1].[programid] ) [t2] order [t2].[program] i have thought sql below far cleaner i'm not sure of linq statement achieve it. select distinct o.programid, t.program table1 0 inner join table2 t on t.programid = o.programid order t.program thanks in advance i don't know if help, can try this; var result = (from o in table1 join t in table2 on o.programid equals t.programid orderby t.program select new { o.programid, t.program }).distinct();

linux - PHP and the build process (/.configure, make and install): orientation, please -

i'm newbie , after i've learnt enough build simple useful web services, managed put myself in position need configure own php build. the problem don't know build means --never built either. my broad question is: step step tutorial doesn't "must have dependencies"? my specific question is: instance, 1 shows how build php odbc, rebuild (configure.nice , make nice?) imap in addition. if finds php bundle comes odbc, great; odbc & imap, better. i'm looking show me how fish. please. thnx. a. gazler correct, simple setup, can configure ubuntu through repositories via apt-get. rhel-based systems - yum equivalent. however, if wanting know more of how compile scratch (which give more control on installation), can so. basics of compiling application: download source website (such php, www.php.net) untar source ( tar -xzvf source.tar.gz ) cd source configure source ( ./configure [install-option-flags] ) compile source ( make ) te

visual studio - LINQ to XSD in VS 2010 -

Image
how use linq xsd in vs2010. last know install linqtoxsd in vs2008 . there updated in vs2010?. the current version 2.x .net 4.0 there samples , docs if download source.

git filter branch - How to detach subdirectory in Git but keep all branches -

i have been following answers question detach subdirectory separate git repository , had successes simple subdirectories on 1 branch confronted subdirectory littered on multiple branches simple git filter-branch --subdirectory-filter subdirectory head does not job. do have switch each , every branch , run filter-branch command or there can blanked change through complete history ? the head @ end of command specifying ref process. can give number of other commands, including --all specify absolutely everything, --branches specify branches, or --remotes specify remotes. may have prefix these options -- tell filter-branch these rev-list args. note --all try process tags explicitly, may not want. use --branches --remotes specify non-tag refs instead. may want add --tag-name-filter cat rewrite tags point rewritten commits - original command leave tags unchanged.

iphone - How to set VoIP mode on a socket in iOS 4 -

i'm trying set socket in voip mode on iphone, app can woken when event happens. have simple server write socket if , if app should wake , talk main web service something. calling cfreadstreamsetproperty() on stream attached socket seems return zero, if i'm not mistaken false, meaning stream did not recognize and/or accept property value. read in previous question facility not available on simulator, tried on real phone, same result. how can figure out why call failing? the code below: - (id) init { nslog(@"notificationclient init, host = %@", [self getnotificationhostname]); cfhostref notificationhost = cfhostcreatewithname(kcfallocatordefault, (cfstringref)[self getnotificationhostname]); cfstreamcreatepairwithsockettocfhost(kcfallocatordefault, notificationhost, [self getnotificationport], &_fromserver, &_toserver); bool status; status = cfreadstreamopen(_fromserver); status = cfreadstreamsetproperty(_fromserver,

wolfram mathematica - Combinations with repetition -

i'm using mathematica 7 , combinatorica package function can combinations of number list of elements order doesn't matter , there no repetition.e.g: in: ksubsets[{a, b, c, d}, 3] out: {{a, b, c}, {a, b, d}, {a, c, d}, {b, c, d}} i cannot find function give me combinations of number list of elements order doesn't matter , there is repetition. i.e. above example include elements {a,a,b},{a,a,a},{b,b,b}...etc in output. it may require custom function. if can come 1 post answer don't see obvious solution. edit: ideally output not contain duplication of combination e.g. tuples[{a, b, c, d}, 3] return list contains 2 elements {a,a,b} , {b,a,a} combinations point of view same. deleteduplicates[map[sort, tuples[{a, b, c, d}, 3]]]

django - 'QuerySet' object has no attribute ERROR, trying to get related data on ManyToMany fields -

i have following models: class tag(models.model): tag_name = models.charfield(max_length=250) tagcat = models.foreignkey('tagcat') class subject(models.model): user = models.manytomanyfield(user) tags = models.manytomanyfield(tag) class tagcat(models.model): cat_name = models.charfield(max_length=100) so have subject, has tag. want loop subjects , appropriate tags, trying construct right view. far, have: def home(request): user1 = subject.objects.filter(id=1) print(user1.tags.all()) i expect tags of user through print statement, instead error 'queryset' object has no attribute 'tags' how getting 'subject' objects respective tags , pass them template? (ideally subjects. did 1 here, simplify process of troubleshooting) filter returns queryset (as may have guessed), want get instead user1 = subject.objects.get(id=1) if subject not exist subject.doesnotexist exception. there's get_obj

Simple Android Spinner code -

i have written simple spinner wrapper, wondering if of experts out there think of ways make more robust. handles strings @ moment, first enhancement... anyway, code (shamefully badly named) myspinner class is: package a.b.c; import android.content.context; import android.util.attributeset; import android.widget.arrayadapter; import android.widget.spinner; public class myspinner extends spinner { // constructors (each calls initialise) public myspinner(context context) { super(context); this.initialise(); } public myspinner(context context, attributeset attrs) { super(context, attrs); this.initialise(); } public myspinner(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); this.initialise(); } // declare object hold data values private arrayadapter<string> arrayadapter; // add selected item end of list public void additem(string item) { this.additem(item, true); } public void additem(string item, boolean s

linear algebra - How to solve an equation of the form p = aw + bx + cy + dz where I have thousands of a-e data sets? -

i have thousands of data sets of (p, w, x, y, z), , i'm pretty sure fit equation of form p= aw + bx + cy + dz , p rounded in way. i'd write program solve constants a, b, c, , d, given data sets variables , result have. alternatively, if there software can this, great. suggestions, or google keywords can use further research? notice that, if points fit equation perfectly, need 4 data determine parameters , not "thousand". remaining points either fit equations (hence redundant) or cannot made fit equation (i.e. problem impossible) if instead fit you're looking not perfect , need find parameters a,b,c,d optimal fit (i.e. minimize square errors), need linear regression. please notice each of equations define 1 of datapoint can written in form ax = b where row-vectors of 4 values , x column-vector of 4 values. reason, the vector summarizes info in writing carried tuple (a, b, c, d) the vector x summarizes info in writing carried tuple (w, x,

python mysqldb problem interfacing with python 2.6 & or mysql -

i have mysql & mysqldb installed python 2.6 & django 1.2.3. can open & log on mysql no problem it's not interfacing python when check see if it's working in python interpreter. error msg getting when invoke in interpreter.... import mysqldb traceback (most recent call last): file "<stdin>", line 1, in <module> file "/opt/local/library/frameworks/python.framework/versions/2.6/lib/python2.6/site-packages/mysqldb/__init__.py", line 19, in <module> import _mysql importerror: dlopen(/opt/local/library/frameworks/python.framework/versions/2.6/lib/python2.6/site-packages/_mysql.so, 2): library not loaded: /opt/local/lib/mysql5/mysql/libmysqlclient_r.15.dylib referenced from: /opt/local/library/frameworks/python.framework/versions/2.6/lib/python2.6/site-packages/_mysql.so reason: image not found looks using macports python installation on macos x. if use macports upgrade, should not run problems that. fir

performance - Eclipse indexing takes forever -

i have eclipse helios sr1 installed on ubuntu 10.04 desktop , i'm having work huge set of web projects in it. when import projects eclipse builds workspace keeps consuming 100% of cpu invariably. after checking happening found in eclipse's progress tab there couple of endless tasks: system: java indexing... n files index system: updating jsp index system: persisting jsp translations these tasks seem never end , makes eclipse unusable. i doubt memory issue, have 2gb in machine , eclipse's heap size not greater 350mb , xmx set 1024mb. also tried running eclipse different vm versions: sun's 1.6, sun's 1.5, , open jdk 1.6. no changes. i have athlon x2 2.2ghz processor , 7200 rpm samsung hard drive. the source code shared via svn. does have idea of going on? this eclipse.ini in case: -startup plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar --launcher.library plugins/org.eclipse.equinox.launcher.gtk.linux.x86_1.1.1.r36x_v20100810 -pr

java - Email multiple recipients without revealing other recipients -

i'm using javamail send emails list of recipients, don't want them able see else received email. don't want send using bcc since user doesn't see in list. thought code it, shows recipients in list. other creating loop , sending emails 1 @ time, there way this? (note: recipients[] string array containing email addresses.) javax.mail.internet.internetaddress[] addressto = new javax.mail.internet.internetaddress[recipients.length]; (int = 0; < recipients.length; i++) { addressto[i] = new javax.mail.internet.internetaddress(recipients[i]); } msg.setrecipients(javax.mail.message.recipienttype.to, addressto); no, there isn't way email. you have explicitly build , send email iterating each of recipients, 1 of them sole member of addressto array.

jQuery resizable's alsoResize: How can I cut the growth ratio of the inner resize div's? -

i've resizable area contains 2 areas want resized side side. ratio of growth horizontally 1:1 each area, since 2 contained areas side side, sum of widths grows twice fast container. how cut horizontal growth of 2 contained areas in half. <html> <head> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/base/jquery-ui.css" type="text/css"/> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script> </head> <body> <style> #resizable { background-position: top left; } #resizable { width: 300px; height: 120px; padding: 0.5em; } #also1, #also2 { width: 75px; height: 60px; padding: 0.5em; } #resizable h3, #also1 h3 , #also2 h3 { text-al

[Python]How to convert/record the output from subprocess into a file -

i using subprocess module, popen class output results like: 063.245.209.093.00080-128.192.076.180.01039:http/1.1 302 found 063.245.209.093.00080-128.192.076.180.01040:http/1.1 302 found and here script wrote: import subprocess, shlex, fileinput,filecmp proc = subprocess.popen('egrep \'^http/\' *', shell=true, stdin=subprocess.pipe, stdout=subprocess.pipe,) stdout_value = proc.communicate()[0] print 'results:' print stdout_value my question is: how convert/record results stdout file? i appreciate responses , helps! import subprocess import glob def egrep(pattern, *files): """ runs egrep on files , returns entire result string """ cmd = ['egrep', pattern] filespec in files: cmd.extend(glob.glob(filespec)) proc = subprocess.popen(cmd, stdout=subprocess.pipe) return proc.communicate()[0] results = egrep(r'^http/', '*') print 'results:' print result

c++ - How to get HWND in win32? -

is there way hwnd handler of window? i'm using win32. you call getactivewindow active control in application, repeatedly call getparent on returned handle until returns null. last valid handle should handle of main window. the easier way else said store returned value createwindow somewhere.

asp.net - Picture or photo viewer on my Web site -

lets let customer upload 5 pictures. i'm looking way let visitors see images 1 one. i've seen some.. there thumbnails on side/bottom (that looks vertical/horizontal film strip) , default picture large 1 displayed. , viewers can click others show pictures. this possibly ajax solution. couldn't come right keywords google custom web component. perhaps "photo gallery". more interested know solutions developers here use site. perhaps lightbox keyword you're looking for: http://www.google.com/search?q=lightbox

android - I'm using onSensorChanged(). What should I specify in <uses-feature>? -

i've checked doc here: http://developer.android.com/guide/topics/manifest/uses-feature-element.html and found 2 relevant features: 1) android.hardware.sensor.accelerometer 2) android.hardware.sensor.compass which 1 need specify in manifest? or both? yes, i'm sure i'm using accelerometer. accelerometer , magnetic field values used calculate "direction" (which means i'm using android.hardware.sensor.compass ??) here's code: @override public void onsensorchanged(sensorevent event) { int type = event.sensor.gettype(); switch (type) { case sensor.type_magnetic_field: mags = event.values.clone(); break; //i'm using accelerometer here case sensor.type_accelerometer: accels = event.values.clone(); break; } sensormanager.getrotationmatrix(rotationmat, i, accels, mags); sensormanager.getorientation(rotationmat, calculatedorients); //i direction he

mail server - Postfix and sending incoming emails to script instead of sending -

i want use postfix accept incoming emails , have send them external python script parse them , add them database. i read done via policy file. my first question should policy file return have postfix delete email queue success message sender. my second question can use policy file validate smtp authentication sent client? if not, there way of having use external script validate login? thanks! christian if need smtp authentication anyway , want script act mda , think can setting mailbox_command = /path/to/my/script in /etc/postfix/main.cf , configuring authentication scheme. if have dovecot running, too, can recommend having postfix authenticate via dovecot , configurable when comes sasl authentication. update since having plaintext passwords going on wire (assuming service reachable network), recommend permitting authentication on encrypted line. configuration i'm going show still accept mails server destination without authentication. far know, beh

iphone - Determine whether UITableViewCell is editing from "swipe" or "self.editButton" -

i'm trying determine whether uitableviewcell subclass in edit mode user's swipe (in case don't need indent subviews) or user pressing "edit" button associated uitableviewcontroller. (in case do.) i know it's possible cell's perspective, since self.textlabel view automatically indents properly. have tried: -(void)layoutsubviews { [super layoutsubviews]; cgrect labelframe = self.textlabel.frame; labelframe.origin.x += 5; mycustomuilabel.frame = labelframe; } but custom label not indent. (though self.textlabel view does?) i avoid following: providing cells reference parent table. overriding methods in uitableviewcontroller class let cells know whether being edited individually or entire table editing. you can override willtransitiontostate: in uitableviewcell subclass. when "edit" button pressed state uitableviewcellstateshowingeditcontrolmask (=1) , when swiping uitableviewcellstateshowingdeleteconfirmatio

android - How to set zoom level of a Google map according to marker locations -

i have placed 2 markers on google map. 1 in usa , other 1 somewhere in asia. google gives zoom levels 1, 2, 3, 4, 5, 6, etc. i don't want hard-code zoom level. how can display markers depending upon distance? i.e. if 2 items close each other or in same city, close zoom level should used, , if they're far apart, maximum zoom level should used. what using generate maps? i'm making use of gmap2 api in project of mine 8 months back, , looks had call 'gdirections(map{{div}});' on, well, map div in order display route between 2 locations, , adjust level of zoom appropriately.

java me - How we can pass command line argument in j2me application? -

how can pass command line argument in j2me application ? there no "command line" pass arguments from. need design program differently; ask user @ start of program information need. in general, j2me not used same kinds of things j2se command-line programs. there no way (normally) user view standard output or supply standard input. study midlet api carefully.

MSMQ really slow performance with Recoverable=true -

the performance of microsoft message queue (msmq) @ least factor ten slower, if enable persistent messages, setting recoverable attribute true. did expect drop in performance, since messages written disk instead of being stored in memory, much. can make performance tuning of message queue? edit: messages 2 kilobytes each. in-memory version can create 10 messages per second. message stored on disk, speed 1 per second. i completede agree, performance penalty expected, think 10 messages per second slow, thought sevice writing messages, bottleneck. non-recoverable messages still written disk msmq doesn't wait confirmation of success. "why express msmq messages being written disk?" 10 express messages per second incredibly slow, 1 recoverable message per second. there wrong machine using, or service. on desktop machine, can send 1,000 recoverable 2kb messages in 6-7 seconds. cheers john breakwell

javascript - RegExp: Different results when using Backreference -

see http://jsfiddle.net/aeeun/ why when use backreference vs no backrefences, different results? var str = "hello world\nhello "; document.write("without backreference: <br />"); var match = str.match(/\s(?![\s\s]*\s)/); document.write("- match.index: " + match.index + "<br />"); // index 16 document.write("with backreference: <br />"); var match = str.match(/(\s)(?![\s\s]*\1)/); document.write("- match.index: " + match.index); // index 6 the difference constrain 2 character same. in first regular expression there must not any non-whitespace character following: /\s(?![\s\s]*\s)/ this means match non-whitespace character not followed other non-whitespace character. that’s why matches last o followed whitespace: "hello world\nhello " ^ no other non-whitespace character following but in second regular expression there must not specific

locking - C# TPL Multiple List Enumerators One Modifier Without Starvation -

i have several threads created through tpl (probably not relevant). threads interact particular object enumerating on contained list without ever modifying anything. other threads add or remove items list. currently, have lock statement around code segments enumerate list , lock statements around code segments modify list. i'm not experiencing performance problems that's that. however, realize more-efficient solution allow many concurrent enumerators , lock out else when modifying list. currently, 1 thread may enumerating list @ given time. future reference, pattern allows this? important . there many solutions work fine in lot of cases won't work mine. in application, there chance barrage of readers never stop -- starving modifiers. i'm looking for: enumerate 1 enumerate 2 concurrent 1 modify 1 request queued enumerate 3 request queued because of modify request enumerate 4 request queued modify 2 request queued enumerate 2 finishes enumerate 1 finish

iphone - Why NSCalendar's dateFromComponents returns wrong date? -

i expecting 2010-10-11 00:00:00 but instead receive 2010-10-10 21:00:00 +0000 i know, can add few hours , receive desired date, not understand why previous day 21 hours... please, help! nsdatecomponents *comps = [[nsdatecomponents alloc] init]; [comps setyear:2010]; [comps setmonth:10]; [comps setday:11]; [comps sethour:0]; [comps setminute:0]; [comps setsecond:0]; nscalendar *cal = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; nsdate *retdate = [cal datefromcomponents:comps]; i think problem may solved setting nstimezone .

sql server - What is the use of this table: 'Master.dbo.spt_Values'? -

possible duplicate: what purpose of system table table master..spt_values , meanings of values? could tell me use of table in sql server database? i'm pretty sure it's lookup table sql server configuration options.

sphinx4 - Speech Recognition through sphinx 4 -

hey has used sphinx 4? want use project, installed , run helloworld demo, problem works fine first , second times when execute third time, doesnt recognise anything. idea why happening? have created sphinx library , 1 should imported in project ? have implemented in project of mine , works fine. here link learned it: http://www.youtube.com/watch?v=z0f3vvcjwyo . , used one: http://dipayandev.blogspot.ro/2012/03/speech-recognition-by-java-sphinx4.html ( wich explains how can change grammar file, recognize whatever want ). i know created user library in java , went on quite good. also, try building program scratch( meaning write hello world class in java ). hope helps out. luck. p.s: try adding additional heap memory jvm right clicking on project: run as-> run configuration-> arguments , type -mx256m.

Reboot system with Assembly -

i have question. can reboot system (os: ms windows xp/7) assembly? how?? (can give me .com file?) it can't done .com file, because .com file ms-dos program , doesn't have access necessary windows apis. can done .exe file though. if know how call windows apis assembly, looks exitwindowsex function might want.

couchdb - Getting UUIDs in a CouchApp with active vhost -

i looking right way loading new uuids or accessing _session object in couchapp behind vhost. i have written couchapp , workes normal ugly urls. if use http://example.cloudant.com/mydb/_design/myapp/index.html address works expected. if use www.mycouchapp.com ( mycouchapp.com cname -> example.cloudant.com/mydb/_design/myapp/_rewrite ). cannot access ressource in top level of couchdb _session, _stats, or _uuid because of security limitations cannot make rewrite-rule "from":"_session", "to": "../../../_session" because more "../../" not allowed. is there way or workaround problem? you should use couchdb's url rewriting , vhost possibilities: http://blog.couchone.com/post/443028592/whats-new-in-apache-couchdb-0-11-part-one-nice-urls hth cheers andy

c++ - Problem with OpenCL kernel recompile slowing down program and possible memory issues because of that -

i'm new opencl , i'm running os x 10.6 nvidia 330 graphics card. i'm working on cloth simulation in c++ i've managed write kernel compiles , runs. problem it's running slower did on cpu without opencl. believe reason every time call update() method calculations i'm setting context , device , recompiling kernel source. to solve this, tried encapsulating various opencl types needed cloth simulation class try , store them there, , created initcl() set these values. created runcl() execute kernel. strangely gives me memory problem when separate opencl stuff 2 methods. works fine if initcl() , runcl() both combined 1 method though why i'm little stuck. the program compiles , runs sigabrt or exc bad access @ point marked in runcl() code. when sigabrt error cl_invalid_command_queue can't work out life of me why happens when split 2 methods. sigabrt when assertion fails expected other times bad memory access error when trying write buffer. also if can

c++ - Should an octree be rebuilt every frame? -

when using octree collision detection in game, should tree rebuilt every frame or there better way assuming half objects move in frame? if scene changes every frame, have redo tree.

c++ - Efficient exit from multithreaded application (specifics) -

i've read few sources on proper methods of bubbling message out thread other threads exit gracefully (every thread performs it's own exit routine). of these, liked idea of global atomic boolean can flagged thread, , other threads check flag perform exit routine - when threads joined, main thread can exit application. purely computation threads handled differently, right? is efficient , safe? there better way this? thanks! in windows, use queueuserapc call function throws exception, causing threads exit cleanly. i wrote more details in answer here: how guarantee fast shutdown of win32 app? in summary, here's happens: say thread wants terminate thread b (and c, d, ...) thread calls queueuserapc() , passing handle thread b , address of function throw exception of class mythreadexit. thread b runs until calls checks alertable waits. maybe waitforsingleobjectex , maybe sleepex , or else. at point, thread b runs apc function passed earlier, causing

Put 2 jquery functions in 1 function -

i have 2 functions. how can make 2 jquery effects / functions: 1 jquery code. // function 1. hover on .landkaart var hover = false; $(".landkaart > ul > li > a").hover(function () { if ( hover == true ) { $(this).closest("li").removeclass('open'); hover = false; } else { $(".landkaart ul li .pijl").hide(); $(this).closest("li").addclass('open'); console.log(this); $(".pijl").show(); hover = true; } }); // interval .landkaart var listitem = $(".landkaart > ul > li"), len = listitem.length, index = 0; $(".landkaart > ul > li:first").addclass('open'); setinterval(function () { $(".landkaart > ul > li").removeclass('open'); if ( (index + 1) >= len ) { index = 0; $(".landkaart > ul > li:first").addclass('open

Django: searching on an EncryptedCharField (django-extensions), is this possible? -

is possible? for model encryptedcharfield named "first_name" notice field not decrypt when search on it. in other uses fine. not work: if form.is_valid(): cd = form.cleaned_data search_results = mytable.objects.filter(first_name__icontains=cd['search_term']) is design or doing wrong? help... encrypting search term first, if exact decrypted value, not work cipher not going same 1 stored in db. not work: crypter = crypter.read(settings.encrypted_field_keys_dir) if form.is_valid(): cd = form.cleaned_data cipher = crypter.encrypt(cd['search_term']) search_results = mytable.objects.filter(first_name__icontains=cipher) when encrypted (or @ least, when done properly), impossible gain value has been encrypted, without knowing value. means while can check value of password quickly, user has given value of password, hard find out value of password encrypted string. part of p=np topic. when search via mytable.objects.filter(f

PHP / MySQL SELECT query using email address mystery -

i have particularly puzzling problem. i using php loop through recordset , identify if email address exists in table. the code works fine until gets 1 particular email address , can't life of me see wrong. the email address marcodambrosio@domain.com. following error: you have error in sql syntax; check manual corresponds mysql server version right syntax use near 'ambro'' @ line 1 all other email address fine. i echo query select * user_details email='marcodambrosio@domain.com' and run in navicat , works php code follows: if (!function_exists("getsqlvaluestring")) { function getsqlvaluestring($thevalue, $thetype, $thedefinedvalue = "", $thenotdefinedvalue = "") { if (php_version < 6) { $thevalue = get_magic_quotes_gpc() ? stripslashes($thevalue) : $thevalue; } $thevalue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($thevalue) : mysql_escape_string($thev

classpath - fitnesse not able to refer external API's in Java? -

fitnesse not able test application. working on java , have defined 3 things in class path : 1) path fitnesse.jar 2) path jar file(xstream.jar) code requires. (this jar included in build path of project also). 3) class path of fixture class. fitnesse showing "java.lang.noclassdeffounderror: com/thoughtworks/xstream/xstream " can please help, thing has made whole work stuck !!! i had recentley similar problems. resolution set correct working dir. got work use of followin start bat: call java -dbasedir=d:\mybasedir -dmypath=d:\mybasedir\somesubdirs\bin -dmylibrarypath="%path%;.;d:\mybasedir\somesubdirs\lib" -jar d:\mybasedir\fitnesse\fitnesse.jar -d d:\mybasedir\fitnesse\ -r mysuite -p 8080 be aware of start parameters: -d used working dir. perhaps gives further idea look.

SQL Server Connection String - Different Domain -

i have sql server connection string in config file: <add name="dbmaster" connectionstring="data source=servername\namedinstance;initial catalog=somedb;integrated security=sspi;" providername="system.data.sqlclient"/> this fine if running domain sql server located, receive following error on different domain: system.data.sqlclient.sqlexception: error has occurred while establishing connection server. when connecting sql server 2005, failure may caused fact under default settings sql server not allow remote connections. (provider: sql network interfaces, error: 26 - error locating server/instance specified) there trust between domains. i tried following no success: <add name="dbmaster" connectionstring="data source=servername.domain.com\namedinstance;initial catalog=somedb;integrated security=sspi;" providername="system.data.sqlclient"/> i can ping servername.domain.com. i h

php - Dates do not post right -

i seem going no place fast... can't seem single inline(embeded) jquery datepicker datetext post php , mysql correctly return data table.. reading has me understand should right, not. datepicker select have several events trigger single select... data being requsted day, month, , year sending date create highcharts graph of data hours of day, days of month, , months of year. the table simple... date, time, power here javasctipt... $(document).ready(function () { $('#datepicker').datepicker({onselect: function(datetext) { var mydate = $(this).datepicker('getdate'); $('#apdiv1').html($.datepicker.formatdate('dd, d', mydate)); $('#apdiv5').html($.datepicker.formatdate('mm', mydate)); $('#apdiv7').html($.datepicker.formatdate('yy', mydate)); $.post('daypower.php', {choice: datetext.val}, function(data) { $('#apdiv2').html(data).show();

python - Most efficient way to open a file and read the lines? -

i've got this: vlgastream = open('vlgachcwaves.txt', 'r+') vlgabuffer = vlgastream.readlines() vlgastream.close() but need way directly , efficiently read of lines file buffer? iterating on file yields lines. with open('vlgachcwaves.txt', 'r+') vlgastream: line in vlgastream: dosomethingwith(line)

JQUERY / ASP.NET: Reshowing the jquery dialog after an asp.net occurs? -

can tell me easiest way display jquery dialogafter postback occurs. basically showing asp.net controls inside jquery dialog , when click event occurs in asp.net but of course after postback has finished screen brought without jquery dialog.. design presume wondered if there way around this? i using updatepanel (asp.net). any ideas appreciated? thanks you use scriptmanager.registerstartupscript load popup. see documentation

JQuery function or functions for dates -

i building custom user control in asp.net user can enter in date. using jquery function puts in date mask in format of dd/mm/yyyy, unable find jquery function(s) or 1 combines needs. what looking is: 1) validate whether date date, i.e. not 31/13/2010 or along lines. 2) can check see whether date in past or in future based upon configuration entry in application. can me, please? this off top of head, use javascript's date object http://www.w3schools.com/jsref/jsref_obj_date.asp 1) use 1 of following var d = new date(datestring); var d = new date(year, month, day, hours, minutes, seconds, milliseconds); then verify date components same entered. if set month 50, take year, , go 50 months forward... seems odd, but... have verify information entered. months start @ 0 january, when checking, aware of that. 2) there's lot of ways check, quick thought on is var t = d.gettime() - new date().gettime(); if t positive, it's in future, if it's negat

android - drawable vs. drawable-ldpi/drawable-mdpi -

all android docs mention "drawable" directory. however, when create android project in eclipse, doesn't create "/res/drawable" directory, create "/res/drawable-ldpi" , "/res/drawable-mdpi". imagine have pixel resolution, what's going on here? when i've stepped through tutorials, i've manually created "drawable" directory , put resources in there, did need to? references "/res/drawable/" work if "drawable-{l|m}dpi" present? i believe added in android 1.6. it's explained here: http://developer.android.com/guide/practices/screens_support.html

Using Facebook Connect to write user's name onto my website -

hi i've set facebook connect on website, , want when facebook user logs in, "welcome 'user name'" appear. ideas? here documentation of getting user info via facebook connect http://developers.facebook.com/docs/reference/rest/users.getinfo hope helps

c++ - Statically linked xerces 3.0.0 does not work while dynamic works on Linux -

so trying statically link xerces 3.0.0 on linux. i did dynamic link , works, in order avoid dependancy want statically. i changed of make files in appropriate way -wl,-bstatic ... -lxerces-c -wl,-bdynamic ... but getting following errors: undefined reference '__ctype_b' undefined reference '__ctype_tolower' undefined reference '__ctype_toupper' i fixed brute force method found here but there type of errors related xerces. xerces/3.0.0/lib/libxerces-c.a(posixmutexmgr.o): in function `xercesc_3_0::posixmutexmgr::create(xercesc_3_0::memorymanager*)': posixmutexmgr.cpp:(.text+0x84): undefined reference `pthread_mutexattr_init' posixmutexmgr.cpp:(.text+0x95): undefined reference `pthread_mutexattr_settype' posixmutexmgr.cpp:(.text+0xad): undefined reference `pthread_mutexattr_destroy' posixmutexmgr.cpp:(.text+0xd0): undefined reference `pthread_mutexattr_destroy' it seems missing pthread tried adding not fix problem..

c++ - float bits and strict aliasing -

i trying extract bits float without invoking undefined behavior. here first attempt: unsigned foo(float x) { unsigned* u = (unsigned*)&x; return *u; } as understand it, not guaranteed work due strict aliasing rules, right? work if take intermediate step character pointer? unsigned bar(float x) { char* c = (char*)&x; unsigned* u = (unsigned*)c; return *u; } or have extract individual bytes myself? unsigned baz(float x) { unsigned char* c = (unsigned char*)&x; return c[0] | c[1] << 8 | c[2] << 16 | c[3] << 24; } of course has disadvantage of depending on endianness, live that. the union hack undefined behavior, right? unsigned uni(float x) { union { float f; unsigned u; }; f = x; return u; } just completeness, here reference version of foo . undefined behavior, right? unsigned ref(float x) { return (unsigned&)x; } so, possible extract bits float ( assuming both 32 bits wide , of course

How can I strip all punctuation from a string in JavaScript using regex? -

Image
if have string type of non-alphanumeric character in it: "this., -/ #! $ % ^ & * example ;: {} of = -_ string `~)() punctuation" how no-punctuation version of in javascript: "this example of string punctuation" if want remove specific punctuation string, best explicitly remove want like replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"") doing above still doesn't return string have specified it. if want remove spaces left on removing crazy punctuation, going want like replace(/\s{2,}/g," "); my full example: var s = "this., -/ #! $ % ^ & * example ;: {} of = -_ string `~)() punctuation"; var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,""); var finalstring = punctuationless.replace(/\s{2,}/g," "); results of running code in firebug console:

asp.net - How does IIS7 determine the same session in a cookieless scenario? -

we have asp.net cookieless sessions (inproc), url contains session id, i.e. s(dfasfdafasdfasfa) we have several clients going through proxy servers appears our web server doesn't recognize session id , without session data can't continue. i've tested our sites on open proxies , work fine. there going on particular client proxy server causes behavior. i've examined package captures success , fail cases (provided client) , raw html getting transmitted, including headers, same. proxy server not appear caching urls because correct session id coming down. so thought iis7 using in addition session id in url determine unique client. perhaps @ tcp/ip level? rather app(http) level. on track? know answer this? unfortunately without being able recreate scenario locally i'm racking brain hard. log request url , sessionid , isnewsesssion .... should tell problem lies. i doubt see valid session presented in url not reflected in sessionid. if see value ex

asp.net - Why is the page at one URL using the cached page from another URL? -

background i'm pretty new asp.net , new concept of caching. i'm hoping knows they're doing, problem here obvious. using mcms 2002, built template.aspx page receives "person_id" query string , builds pages accordingly. several different departments @ school work using template display faculty biographies. working correctly. the problem the problems start happening when try caching page. when person visits person_id=16175 on 1 department's page, visits same numeric bio on different department page, loads cached page instead of rebuilding it. problem, then, has of wrong department branding. example: http://health.usf.edu/medicine/obgyn/facstaf/profiles.htm?person_id=16175 http://health.usf.edu/medicine/surgery/surgery_bios.html?person_id=16175 it's same person_id, urls different. great if template recognize different urls , ignore cache. i'm assuming problem lies in fact both pages being built using same aspx page on backend. her

ruby on rails - HTTP basic auth for Capybara -

i'm writing rspec tests rails 3 application , trying switch webrat capybara . far application uses http basic auth authorize admin user, idea how can test capybara? here current webrat step: it 'should authenticate admin' basic_auth('user', 'secret') visit '/admin' response.status.should eql 200 response.status.should_not eql 401 end how do capybara? thanks! i got work using page.driver.basic_authorize(name, password) instead update : at moment, after capybara upgrade, i'm using pile of workarounds: if page.driver.respond_to?(:basic_auth) page.driver.basic_auth(name, password) elsif page.driver.respond_to?(:basic_authorize) page.driver.basic_authorize(name, password) elsif page.driver.respond_to?(:browser) && page.driver.browser.respond_to?(:basic_authorize) page.driver.browser.basic_authorize(name, password) else raise "i don't know how log in!" end

python - Regular expression for a string like this -

i need match strings start with: '/engine and end with: ir_vrn' i have used this: vrn_page = re.compile('\'/engine[a-za-z0-9._+-&/?:=]+ir_vrn\'') traceback (most recent call last): file "<stdin>", line 1, in <module> file "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) file "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: bad character range but doesn't work string: '/engine/page/im/pop_mostra.php?p_=9078&p_utentevisitatore=1702795&loto=http://s1.example.com/utloto/9/9078/media/7df4164ecb81a5992280a1ce81120d05-3a5fa4377a23242690a273a82ea5d607&type=ir_vrn' try: /engine.*?ir_vrn note question mark. makes sure in /engined&^& ^& ^&ir_vrn@$@#$@#ir_vrn!@#!@# it catches /engined&^& ^& ^&ir_vrn rather /engined

compiler construction - ARB Fragment If/Else -

i have problem , can't seem wrap head around it, hoping someon here might able me out. i'm writing compiler miniglsl, , far good. i'm @ point need output arb fragment program, problem is, arb have target doesn't support branching. (a full list of supported instructions can found here http://petewarden.com/notes/archives/2005/05/fragment_progra_2.html ). in order simulate if/else, i've been making use of cmp program follows (assuming 0 or greater = true, otherwise, false. // represents comments # causes bad formatting on here): if (a < b) = 1 + 1; if (f < g) c = 2 + 3; else if (h < i) b = 1 + 2; else d = 2 + 3; into arb fragment: temp cond1, cond2, cond3, tempvar1, tempvar2, tempvar3, tempvar4, a, b, c, d, e, f, g; //top if //condition < b slt a, b, cond1; sub cond1, 1.0, cond1; //assign if true add 1.0, 1.0, tempvar1; cmp cond1, a, tempvar1, a; //condition f < g slt f, g, cond2; sub cond2, 1.0, cond2; //if top leve

reflection - c# property override Set method -

i have class below, want override set value of "school,country..etc.." property when 1 sets value , don't want change student class need in base class , use generic method public class student : baseclass { public string school { get; set; } public string country{ get; set; } } ie: when 1 sets student.school="harvard" , need store as student.school="harvard custom value" ; note: calling onpropertychanged in base class rather main class. if want aspects, try postsharp

iphone - passing NSManagedObjects between ViewControllers - random bad access errors -

is passing nsmanagedobjects between viewcontrollers bad idea? have ipad app , seem run random bad access crashes , sigbart errors. these nsmanageobjects coming coredata , wonder if drop out of memory , cause this. hoping pass them controller controller avoid doing fetch on every viewcontroller. sounds it's matter of bad object memory allocation practices. long you're not multithreading app , there 1 managedobjectcontext (typical), can pass these nsmanagedobjects between veiwcontrollers no problem. what's happening you're passing reference 1 viewcontroller without incrementing it's refcount retain message. can dicey. what i'd recommend having retain property on viewcontrollers, like @property (nonatomic, retain) nsmanagedobject *yourobject; then, when managed object, keep this: self.yourobject = ...; ... , when want pass view controller: otherviewcontroller.yourobject = ...; and take care of setting retain/release you.

django celery - how to send request.FILES['photo'] to task -

i'm trying send request.files['photo'], uploaded file site, tcelery via: tasks.upload_photos.delay(img=request.files['photo']) i pickle error because cannot serialize it. way send file task? error: "can't pickle stringo objects" thanks. read file contents string, pack content type in dict , send that.

Unable to create a new Label on a Windows Forms Application when clicking a button (C#) -

i trying add new label when clicking on button. shouldn't difficult can't working :( private void button3_click(object sender, eventargs e) { label label10 = new label(); label10.location = new point(23, 100); label10.text = textbox1.text; parent.controls.add(label10); } i error when trying debug not explicit message: "nullreferenceexception unhandled." not sure may referring... using "new" keyword create new instance, may missing? thanks! is parent null ? on there too. might call this.controls.add(...) .

compilation error in function returning a struct in C -

i keep getting compilation error: error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token on marked line below: //128 bit vector struct (4 integers) typedef struct { int w, x, y, z; } ivector4; ivector4 sseadd(ivector4 &v1, ivector4 &v2) // <-- line { ivector4 vr; asm { mov eax v1 mov ebx v2 // movups xmm0, [eax] movups xmm1, [ebx] // paddd xmm0 xmm1 movups [rv] } return rv; } i can't see what's wrong: seems problem? edit: hi responses. i'm using gcc compiler, , realize assembly code had provided incorrect.i wondering if best use built_in functions -msse/-msse2. also, what's efficient way load , extract values vector such v4si? i'm finding loading , extracting vector costly ooperation. when sse intrinsics, did mean? thanks help. c not have references. need compile c++ those.

Drupal permission, a user case -

the objective of site maintain product listing. each product composes of title , description , quantity (cck field). each product belongs shop . each shop has manager . all products visible all. a manager can add/edit products of own shop . a site admin can create new shops , new managers . how can set permission above scenario? i thinking of using taxonomy shop names, taxonomy access control permission control. not sure whether on right track though... besides, organic groups option? thanks! tac solves problems. i'm using in similar scenario. here's how set up: create new content type "product" fields specified create taxonomy term each shop. enable , require taxonomy on "product" content type create role each shop enable tac role set tac permissions global allow view, deny update, delete, create , list. set tac permissions shop's term allow view, update, delete, create , list. save , rebuild permissi