Posts

Showing posts from January, 2012

Python Matrix, rows and columns -

i have problem matrix: b= [[-2.5, 0.5], #b random matrix [-1.5, -0.5], [-0.5, 0.5]] how can b get: b=[[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]] many thanks >>> b= [[-2.5, 0.5], #b random matrix [-1.5, -0.5], [-0.5, 0.5]] >>> [[[val] val in row] row in b] [[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]] explanation: consider list: >>> oned = [1, 2, 3] you can re-create list comprehension: >>> [val val in oned] [1, 2, 3] then wrap each element in own list: >>> [[val] val in oned] [[1], [2], [3]] extend 2 dimensions.

visual studio - Repainting image after going to full screen and back in C++/CLI -

i'm building application, paints raw bitmap images on label's hdc using strechdibits. ptr = g->gethdc(); dc = (hdc)ptr.toint32 (); setstretchbltmode (dc, coloroncolor); stretchdibits (dc, 0, 0, (int) (labelpictureshow->width), (int) (labelpictureshow->height), 0, 0, width, height, data, bitmapinfo, dib_rgb_colors, srccopy); g->releasehdc (ptr); this way draw whole videostream, 1 picture stream after another, works perfect. have function resize form , label on whole screen realizing full screen, wchich works great when playing video. but, when stop video or send 1 picture , call full scren function. not repaint image , that's problem. tried use paint event, resize event both of form , label painting image again after resizing, nothing works. when fullscreen or normal size, image flashes short moment it's repainted control's color , dissappears. i've tried put painting code stretchdibits everywhere both nothing works. or advice appreciat

c++ - Determining the type from a smart pointer -

i have function takes in 2 template parameters. 1 expected smart pointer, , other expected object type. example, smartptr<myobject> first template parameter , myobject second template parameter. template <typename t, typename tobject> i know whether can determine second parameter, myobject , automatically first parameter smartptr<myobject> or not template function written this: template <typename t> and type tobject in original template function automatically determined t expected smart pointer. as requested, here function declaration , use: template <typename t, typename tobject> t* createormodifydoc(t* doc, myhashtable& table) { t* ptr = null; if (!table.findelement(doc->id, ptr)) { table.addelement(doc->id, new tobject()); table.findelement(doc->id, ptr); } return ptr; } if know first template parameter smart pointer type, why not declare function 1 parameter , use s

ruby on rails 3 - Log incident when an account is locked after three failed attempts with Devise -

i want log in database incident when users account locked, i'm using rails3 , devise, think i'll need override action in devise controller, don't know wich controller/action , how capture users id. tips? i know old question, easiest approach override lock_access! lockable mixin (in user model): def lock_access! super # record account lock here end

php - How to select first 10 words of a sentence? -

how i, output, select first 10 words? implode(' ', array_slice(explode(' ', $sentence), 0, 10)); to add support other word breaks commas , dashes, preg_match gives quick way , doesn't require splitting string: function get_words($sentence, $count = 10) { preg_match("/(?:\w+(?:\w+|$)){0,$count}/", $sentence, $matches); return $matches[0]; } as pebbl mentions, php doesn't handle utf-8 or unicode well, if concern can replace \w [^\s,\.;\?\!] , \w [\s,\.;\?\!] .

php - PHPBB 3.0.8 weird error -

no idea why repeating template: check out error here it clean install of phpbb. problem not style have installed, same problem occurs default prosilver style. does default prosilver theme correct? if so, can check index_body.html in new theme installed see if has more 1 header/body/footer. if does, it's same way in templates. if not, mod installed. looks pages showing more 1 html output.

ruby - A Rails 3 Engine-Gem which is Also an Application wants to share a DRY configuration via Mixin -

i have number of engines gems , applications (rails3). gems can installed , dependencies managed via bundler in more 1 application (its whole stack upon multiple applications built). engines take advantage of rails resources - models , such. applications 2 reasons: 1) provide full testing environment isolated including applications can 'rails c' example , 2) in order run things 'rake db:migrate' , seed , more. i want both engine , application inject mixins lower level dependencies. here solution came with. works fine - wondering if has criticisms of approach or best practice share regarding sharing issue or overall idea of engine-gem-applications: the engine: #my_engine/lib/my_engine.rb require 'my_engine/config.rb' module myengine class engine < rails::engine config.to_prepare myengine.inject_mixins end end end the application: #my_engine/config/application.rb require 'my_engine/config' module myengine class ap

apache - Install mod_mono on Mac OSX -

i started develop website mono+asp.net mvc2 on mac osx quite new mono , mac. i have got things working monodevelop. website running ok xsp when run monodevelop. now, trying test apache server, don’t know how set things up. instruction can found old or incomplete. tried few of them, none worked. could please me out? the best way install mod_mono on os x source. there couple steps. first, make sure you've installed xcode (which can found on dvd or 2nd cd came machine or app store) provide gcc , rest of standard toolchain. most of normal in-between steps can skipped, assuming you've installed mono , monodevelop stable release packages. if encounter error later on, you'll want install updated versions of xsp , mono , try again. next, download latest stable release of mod_mono , extract contents of archive (by double clicking on icon) , follow steps 1, 2 & 3 in install file, , should go. entire process took ~5 minutes , running :)

c# - SqlCeCommand nullable values -

my code: sqlceconnection sql = new sqlceconnection(@"data source=c:\db.sdf"); sql.open(); cmd = new sqlcecommand("insert xxx(aaa) values(@aaa)", sql); string param = null; //doesn't work //string param = "blah" //works cmd.parameters.addwithvalue("@aaa", param); cmd.executenonquery(); //(1) sql.close(); (1) throws exception when param null. database allows value in collumn aaa null. how can insert null table xxx ? exception: parameterized query 'insert xxx(aaa) values(@aaa)' expects parameter value not supplied. try using dbnull.value instead: var param = dbnull.value;

javascript - How can I use XMLHttpRequest to grab the title of a page and return it to my page? -

i got basic understanding of ajax down, not sure if there way use read dom , send information used on page... in specific case, links news stories being stored in database, , trying text between <a href> , </a> populated actual title of story. any ideas? thanks first of all, you'll need proxy on own server, because cross-domain requests not allowed. simple proxy echo page you, efficiency, should use regular expressions return page's title, want. example, in php: $text = file_get_contents($_request['newspage']); preg_match("/(?<=\<title\>)[^\>]+/", $text, $matches); if(count($matches)) { echo $matches[0]; } else { echo "unknown title"; } it's easy use - send simple ajax request script newspage parameter, , put result link.

javascript - What is causing this simple animation script to animate improperly? -

i cannot seem figure out making script go wrong... you can find animated version of script here... http://jsfiddle.net/ttjam/21/ you may find live project version here... http://jsfiddle.net/ttjam/22/ the live project located @ http://paysonfirstassembly.com/ as can see, animation not have same visual effect in second link. visual effect wish achieve 1 in first link. willing edit script this, or make changes css did not make initially. min-height:120px; in .dynpanelcontent in css doesn't let work properly. don't understand why... if remove it, works @ least here http://jsfiddle.net/ttjam/22/

iphone - TextField:shouldChangeCharactersInRange:replacementString: return trap! -

im calling uitableviewcell delegate method textfield:shouldchangecharactersinrange:replacementstring: on custom cell has 4 uitextfields , happening once maxlength reached on 1 of fields dose not let enter text in other fields because returning "no" initial if statement thats being satisfied. ideas on how around this? i'm testing on 2 fields @ moment. thank in advance. - (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { int regfieldonelength = [regfieldone.text length] ; int regfieldtwolength = [regfieldtwo.text length] ; if ((regfieldonelength >= maxlength && ![string isequaltostring:@""]) || (regfieldtwolength >= maxlength && ![string isequaltostring:@""])) { if(regfieldone.text = [regfieldone.text substringtoindex:maxlength]){ return no; } if(regfieldtwo.text = [regfieldtwo.text substringtoindex:ma

How can I give parameters to a function of a python script through the command-line? -

currently python script ( taggen ) has 1 function: def sjtag(file,len_tag): import csv reader = csv.reader(open(file), dialect='excel-tab' ) row in reader: qstarts = row[1].split(",")[1:-1] n = len_tag/2 in qstarts: name = row[0] start = int(i)-n if start<0: start = 0 end = int(i)+n if end>len(row[2]): end=len(row[2]) tag = row[2][start:end] print name, i, tag, len(tag) sjtag("qstartrefseqhg19.head",80) i want give file , len_tag parameters of sjtag function using bash comand line, this: python ./taggen qstartrefseqhg19.head 80 how can this, or thing similar? thanks help! sys.argv arguments list, first element being script name. it's list of strings, if of parameters numbers, you'll have convert them using int() or float() . so, if called script s

why x works but is undeclared? c++ -

one of example problems basing program off of secant root finding uses x, doesn't declare it, runs successfully. meanwhile when use same setup error saying x undeclared. why work in example program , not mine? using namespace std; #include<iostream> #include<cmath> #include<iomanip> // declaration of functions used void secant(double, double, double, double, double, double, double&, int& ); double fx(double, double, double, double, double); const double tol=0.0001; // tolerance convergence const int max_iter=50; // maximum iterations allowed // main program int main() { int iteration; // number of iterations double a, b, c, d; // constants in f(x) double x0, x1; // starting values x double root; // root found secant method cout<<"enter a, b, c, , d"<<endl<<"separated space "; cin>>a>>b>>c>>d; cout<<&q

how to import user defined datatypes in header (.h) files to c# -

iam new c# platform. have existing project coded in "c". import functions in existing c code c#. there many user defined datatypes of type struct , enums in header files. want use datatypes in new c# project. how can import datatypes in .h , function in .c files c# c# ood compitable lanague not c, can design classses rather go proceudral way. its better desing classes in c# , put mehods , enums per desing. like if 1 .h = 1 c# class , example. break out .h , .c files in classes , put method according it. hope got point.

ruby on rails - Why is this RSpec test failing? -

i'm in process of learning ruby on rails, treat me total neophyte, because am. i've got user model associated rspec tests, , following test fails: require 'spec_helper' describe user 'should require password' user.new({:email => 'valid_email@example.com', :password => '', :password_confirmation => ''}).should_not be_valid end end the relevant part of user model looks this: class user < activerecord::base ... validates :password, :presence => true, :confirmation => true, :length => { :minimum => 6 } ... end here's catch: if run user.new(...).valid? rails console using arguments above, returns false expected , shows correct errors (password blank). i using spork/autotest , restarted both no avail, test fails running directly rspec . doing wrong here? edit i tried few more things test. fails: u = user.ne

How to debug errors in Erlang? -

i got 1 error when starting gen server, want know how debug it, thanks! i run "example:add_listener(self(), "127.0.0.1", 10999)." after start_link. the error : =error report==== 11-may-2011::13:41:57 === ** generic server <0.37.0> terminating ** last message in {'exit',<0.35.0>, {{timeout, {gen_server,call, [<0.35.0>, {add_listener,"127.0.0.1",10999}]}}, [{gen_server,call,2}, {erl_eval,do_apply,5}, {shell,exprs,6}, {shell,eval_exprs,6}, {shell,eval_loop,3}]}} ** when server state == {state,example, {dict,0,16,16,8,80,48, {[],[],[],[],[],[],[],[],[],[],[],[],[],

php - mod_xsendfile with file url -

the apache mod_xsendfile download script want download file url header("x-sendfile: http://site.com/a.zip"); but not work. shows error 404. can me code? mod_xsendfile doesn't work that. can send files on local filesystem.

html - retrieving just the title of a webpage in python -

i have more 5000 webpages want titles of of them. in project using beautifulsoup html parser this. soup = beautifulsoup(open(url).read()) soup('title')[0].string but taking lots of time. title of webpage reading entire file , building parse tree(i thought reason delay, correct me if wrong). is there in other simple way in python. it faster if used simple regular expression, beautifulsoup pretty slow. like: import re regex = re.compile('<title>(.*?)</title>', re.ignorecase|re.dotall) regex.search(string_to_search).group(1)

javascript - How to invalid 00/00/0000 date in JS -

i using jquery validation plugin. used this post validate dates using plugin. working there problem. accepting 00/00/0000 date well. how can invalid date modifying following function. $.validator.addmethod( "australiandate", function(value, element) { return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/); }, "please enter date in format dd/mm/yyyy" ); maybe can try this, perhaps can works :) function(value, element) { if (!value.match(/^00\/00\/0000$/)) return value; }

c++ - Adding a button to the title bar -

i writing c++ application using qt4 , looking implement gui similar firefox 4. is, need remove default context menu in top left corner of window , replace 3 buttons. if notice button in firefox 4 right @ top in title bar , uncertain how can implemented. it won't easy , not cross-platform. read thread in qt forums.

unicode - Making git diff (NOT difftool) and git log -p work with *.sql files and Windows PowerShell -

i know how configure external tool view differences call git difftool . however, if want see 'dump' of changes entire history of file console window, wanted use git log -p <filename> . problem i'm having *.sql files in windows environment. difftool (using my configured tool) correctly handles unicode file, diff not, think git log -p uses under hood. is there way make git diff 'work' files of given/configured extension know there ansi characters , show actual text changes outputted console (in case windows powershell hosted inside console). note: i've looked @ this question/answer making git diff recognize utf16, couldn't work (both iconv , mktemp not present on system). maybe approach should continue examine/experiment possible solution? or solution ensure files know ansi characters present saved ansi - disappointing lose history have on *.sql files (and other files i'm not aware of stored unicode right - i'm newly converte

php - how insert data from xml to mysql with loops -

enter code here`hi how can me ? have problem in script i want save xml file in mysql db the xml file <?xml version="1.0" encoding="utf-8"?> <style> <settings><style_name>default</style_name> <style_version>1.0</style_version> </settings> <tpl> <tpl_name>body</tpl_name> <tpl_display_area>body</tpl_display_area> <tpl_des>body</tpl_des> <tpl_source><![cdata[< body src ]]></tpl_source> <tpl_name>footer</tpl_name><tpl_display_area>footer</tpl_display_area><tpl_des>footer</tpl_des> <tpl_source> <![cdata[> source footer ]]> </tpl_source> <tpl_name>closing</tpl_name><tpl_display_area>close</tpl_display_area><tpl_des>closing</tpl_des><tpl_source><![cdata[<center><h3>our website close right </h3></center>]]></t

x509certificate - Managing certificates with WCF -

we have central wcf service exposing via nettcpbinding duplex comms clients. we want allow computers on internet communicate wcf service. route going down use x509 certificates secure transport layer , provide client authentication, this: <security mode="transport"> <transport clientcredentialtype="certificate"></transport> <message clientcredentialtype="none"/> </security> at moment we're calling "makecert" generate x509 certs, , having specify certificatevalidationmode="peertrust" round fact generated our own self-signed certificates. my question how should go managing client certificates? don't want each client buy own certificate - there hundreds of them , isn't option. suppose want act our own "root authority", i'm not sure how go this... if don't want make every client buy certificate trusted certificate provider verisign, other 2 option

php - unit testing and Static methods -

reading , picking on unit testing, trying make sense of the following post on explains hardships of static function calls. i don't understand issue. have assumed static functions nice way of rounding utility functions in class. example, use static functions calls initialise, ie: init::loadconfig('settings.php'); init::seterrorhandler(app_mode); init::loggingmode(app_mode); // start loading app related objects .. $app = new app(); // after reading post, aim instead ... $init = new init(); $init->loadconfig('settings.php'); $init->loggingmode(app_mode); // etc ... but, few dozen tests had written class same. changed nothing , still pass. doing wrong? the author of post states following: the basic issue static methods procedural code. have no idea how unit-test procedural code. unit-testing assumes can instantiate piece of application in isolation. during instantiation wire dependencies mocks/friendlies replace real dependencies. proce

c# - How to make a checkbox unselectable? -

i wondering how make checkbox unselectable in c#? thought setselectable(false) or cant seem see method. i found canselect seems read property. thanks you can set enabled property false . ie. checkbox1.enabled = false; edit: slow :p

regex - Java - Regular Expression -

i have regular expression validate email: validemail = ^[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]([^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s\\.]|\\.(?!\\.+?))*[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]@[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s\\.]*[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\\\s-\\.]\\.(?!\\.+?)[^\\^~`'!@$#=%&*()+|{}:;,><?\"\\/\\[\\]\\\\0-9\\s-\\_]{2,40}$$ this validation accepting eg: kate@stack---overlow.com however want restrict domain name after @ , before . have 1 hyphen. update: i not prefer making check using contains rather make part of regex. i'd recommend first validating email address javamail api, described in answer: validate e-mail field using regex . way don't have deal complicated regex handle of details of rfc 822 specification on email addresses. once passes that, add addition

c# - Need to modify my Regex to ignore iframe tags -

hi have free text editor blog posts on website c# code behind. use following regular expression strip html tags out of post security: regex.replace(value, @"<(.|\n)*?>", string.empty); however have requirement allow embedding of youtube videos, use iframe, example: <iframe width="425" height="349" src="http://www.youtube.com/embed/ttbhgiumumu" frameborder="0" allowfullscreen></iframe> could me modify regex allow this? try one: <(?!/?iframe)(.|\n)*?> the (?!/?iframe) negative lookahead, checks < not followed iframe or /iframe . i tested online here on regexr

mysql - What is a common web architecture for java apps? -

im developing java web application, , im researching how should combine different types of technology in order use of single webserver. my plan far have following architecture setup internet -> varnish (reverse proxy) -> apache2 (mod_pagespeed, mod_jk) -> ehcache-web (caching html page fragments,spring-cache) -> tomcat (java appsrv) -> ehcache (cache layer) -> mysql (persistance layer) is there problems design? scaling , clustering when comes that? there other (better) solutions? thanks! i not envision webapp in traditional manner - in terms of service providers , consumers. @ work we've restful api layer running under tomcat, built implementing shindig interfaces. layer interacts mysql mongodb. have near/far caching using memcached, plan move redis given use lot of list , set based operations. layer interfaces twitter , facebook apis (like pushing out status updates). endpoints accessible opensocial compliant rest/xml calls. use newrelic mo

android - Overriding a html5 viewport -

i build simple android webview getting html5-website. website provides following line, seems scale view wrong (on low density device): <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> unluckily attempts scale view down 75% unsuccessful, tried using various combinations of: getview().getsettings().setusewideviewport(true); // used true, false getview().getsettings().setsupportzoom(true); // used true, false getview().getsettings().setbuiltinzoomcontrols(true); // used true, false getview().setinitialscale(0); // used 0, 75, 100, 150 here is there other way of overriding html5 ? regs, rob the correct syntax requires commas. replace semi-colons (;) commas (,) , give try.

jquery - freeing memory after ajax request -

after ajax requst can free memory doing this? function ajax(){ this.url = null; this.data = null; this.success = null; this.global = true; this.timeout = json_timeout; this.cache = false; this.datatype = 'json'; this.type = 'post'; var _this = this; this.send = function(){ var jqxhr = $.ajax({ url : this.url, data : this.data, timeout : this.timeout, cache : this.cache, datatype : this.datatype, type : this.type, global : this.global } ) .success(this.success) .error(function(){ dialog.set_error({ headline : lang.get('hdl_error'), body : lang.get('err_timeout'), btns : [ { value : lang.get('btn_ok'),

ruby - rails 3 mail gem please help! -

ok have 2 emails 1 has japanese , english in both subject , body , other 1 seems in iso-8859-1 when email.subject displays both in console , browser , saves fine in database (mongodb). presume converting utf-8 properly. problem how text_body , html_body same ? if try save email.html_part.decoded database string not utf-8 error. if email.html_part.decoded.force_encoding("utf-8") still error. if email.html_part lets me save database not correct when viewing it. comes out content-type: text/plain; charset=iso-8859-1 content-transfer-encoding: quoted-printable content-id: =0d check!=0d =0d to: joe@hotmail.com=0d subject: save =a32,000 on luxury alaskan yacht holiday! =0d from: canada@travel.co.uk=0d date: tue, 10 may 2011 05:39:24 -0500=0d =0d =0d =0d =0d =0d =0d and japanses 1 comes out this content-type: text/plain; charset=iso-2022-jp content-transfer-encoding: 7bit content-id: from: joe@hotmail.com t

java - GWT: String comparision is not working -

i have following code in presenter in gwt mvp application: public void onfailure(serverfailure error) { string errcode = error.getmessage(); window.alert(errcode); window.alert("server error: pleaseenterquestion"); if(errcode == "server error: pleaseenterquestion") window.alert("same"); else window.alert("different"); } the first 2 alerts same. third alert different . expect same . use equals , not == , compare strings: if("server error: pleaseenterquestion".equals(errcode)) see question more information: how compare strings in java?

java - content provider -

i had created class extends contentprovider. had override 6 functions @override public uri insert(uri uri, contentvalues initialvalues) { contentvalues values; if(initialvalues != null){ values = new contentvalues(initialvalues); }else{ values = new contentvalues(); } sqlitedatabase mdb = mdbhelper.getwritabledatabase(); long rowid = mdb.insert(databasehelper.table_program, null, values); if(rowid > 0){ uri programuri = contenturis.withappendedid(null, rowid); getcontext().getcontentresolver().notifychange(programuri, null); return programuri; } throw new illegalargumentexception("failed insert row " + uri); } private void createdata(){ string = "a", b = "b", c = "c", d= "d"; //how going call content provider let me add in data? } my question how call insert() add data? obtain contentresolver instance via getcontentresolver() insert

php - debug codeigniter with mac gdbp -

having problems getting mac gdbp setup debug local codeigniter stuff. here details on setup: - mamp pro 1.9.2 - php 5.3.2 - xdebug 2.10 installed , showing in phpinfo file beside zend stuff. - config xdebug in php.ini: zend_extension="/applications/mamp/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so" xdebug.remote_enable=on xdebug.remote_autostart=1 xdebug.remote_host=localhost xdebug.remote_port=3003 when open macgdbp , refresh page running on local server variables showing in main window, can't step code or anything. , have red warninng in bottom left corner of macgdbp saying 'can not open file'. i realize rather old post had same problem today , wanted post solution in case others struggle getting right. fixed me removing spaces in path localhost root. there 1 folder space in it, , renamed , restarted servers (mamp) , macgdbp, see code being debugged!

php - Parse HTML without xpath -

i'm trying create simple tool parse html files. specifically, need name attributes out of div tags. my html string varies , don't have control on it, if try , use xpath tend errors html not 100% written correctly. any ideas? thanks, there great class called php simple html dom parser on http://simplehtmldom.sourceforge.net/ works fine invalid html, needs lot of memory parsing long html-files.

iphone - Passing Parameter From a View Back To another View's UITableView's Cell -

i have got 2 view. first: firstviewcontroller second: secondviewcontroller firstviewcontroller uinavigationcontroller 's root controller , inside firstviewcontroller ve got uitableview. when cell clicked in uitableview, view navigated secondviewcontroller . inside secondviewcontroller have uilabel. want assign uilabel's value cell clicked @ firstviewcontroller when button clicked in navigation bar . supposed implement this? i can pass value secondviewcontroller firstviewcontroller creating: secondviewcontroller *sv; sv.somestring = someanotherstring; but can not implement @ secondviewcontroller pass value nsstring in firstviewcontroller. can u me please? thank you. ae ya , there easy way handle this..... you can take global variable in delegate.h file declare variable: @interface smoke_applicationappdelegate : nsobject { uiwindow *window; uinavigationcontroller *navigationcontroller; nsstring *messagestring; //this string variable } @

mysql - Complex query, many joins -

i've been wrestling few hours , i'm hoping can give me fresh insight. have 6 tables follows: table a table b, child of (one-to-many) table c, child of b (one-to-many) table d, child of (one-to-many) table e parent of d, in one-to-[zero-or-one] relationship table f, child of e (one-to-many) basically need select field b c = f. i have tried subqueries, joins, , combination of both, have not got far. ideas appreciated. with information you've presented, how about select * inner join b on b.aid = a.aid inner join c on c.bid = b.bid inner join d on d.aid = a.aid inner join e on e.did = d.did inner join f on f.eid = e.eid c.field = f.field if not need, might want post small subset of data required results.

svn - Subversive Team share for existing projects -

i know question has been asked couple of times, there's that's not clear me team -> share project dialog. sorry repost :) so have bunch of projects managed svn (svn directories present) imported in eclipse through new project dialog. works fine. when using share project wizard, select svn provider, repository, , go through 2 following steps dire "enter commit comment" dialog. don't want plugin make commit, or modification repository. i tried repo have read access , got 405 on mkactivity operation. i tried subclipse, , casually tells me project present on repository , link it, thank much. according other answers there similar functionality in subversion, questions : are steps of share project wizard different in subclipse when detects project exists ? if not there way know ? do go through commit, unchecking every file, , praying plugin doesn't svn add ? precisions the "enable automatic project share" option ticked in svn gen

iphone - Create search field in Tableview -

i creating application table view, has large amount of data in it. because of this, necessary me use search field. does have idea how create search-option in tableview? use uisearchbar property, declare using searchbar = [[uisearchbar alloc] initwithframe:cgrectmake(0,0,320,30)]; and add uiviewcontroller's view subview. after that, use searchbar delegate methods in view controller: -(void)searchbartextdidbeginediting:(uisearchbar *)searchbar { -(void)searchbartextdidendediting:(uisearchbar *)searchbar { -(void)searchbar:(uisearchbar *)searchbar textdidchange:(nsstring *)searchtext { -(void)searchbarcancelbuttonclicked:(uisearchbar *)searchbar check out this tutorial hang of search bar , delegates! edit: method isn't using searchbar in tableview itself, above it. means have put tableview subview of uiviewcontroller, , searchbar subview of same uiviewcontroller well!

ASP.Net MVC3 conditional validation -

i'm having troubles validation on application. let's i've following models: public class company { public int id { get; set; } [required] public string name { get; set; } public string location { get; set; } public list<contacts> contacts { get; set; } } public class contact { public int id { get; set; } [required] public string name { get; set; } [datatype(datatype.emailaddress)] public string email { get; set; } public string telephone { get; set; } public string mobile { get; set; } } now in company create view i've 2 buttons, 1 add contacts company, , 1 create new company. detected button used in controller (both buttons named "button"): [httppost] public actionresult create(string button, formcollection collection) { if(button == "addcontact") { addcontact(collection);

python - calculating the next day from a "YYYYMMDD" formated string -

how can calculate next day string 20110531 in same yyyymmdd format? in particular case, have 20110601 result. calculating "tomorrow" or next day in static way not tough, this: >>> datetime import date, timedelta >>> (date.today() + timedelta(1)).strftime('%y%m%d') '20110512' >>> >>> (date(2011,05,31) + timedelta(1)).strftime('%y%m%d') '20110601' but how can use string dt = "20110531" same result above? in advance. cheers!! here example of how it: import time datetime import date, timedelta t=time.strptime('20110531','%y%m%d') newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1) print newdate.strftime('%y%m%d')

iphone - memory leaks in my strings -

i have in code : nsstring *mystring = @""; .... if (...) { mystring = @" other string"; } ... mystring = @" other string "; is leak, please ? sorry, guys, it's not autoreleased. it's not leaked, it's not autoreleased. code prove it: nsautoreleasepool *pool = [[nsautoreleasepool alloc] init]; nsstring *str1 = @"first one"; // nsstring *str2 = [nsstring stringwithformat:@"the %dnd", 2]; // autoreleasing string [pool drain]; nslog(@"%@", str1); // all's ok nslog(@"%@", str2); // exc_bad_access read strings created @"..." construction @ strings programming guide : the compiler makes such object constants unique on per-module basis, , they’re never deallocated, though can retain , release them other object.

category - What are the MediaWiki functions which alter categories in database? -

i'm working on project change category administration mediawiki neo4j. (to store categories , relations neo4j instead of mediawiki-mysql db) i didn't found special hook mediawiki category creation (when category , categorylinks stored db). try replace functions insert, update , select category table (mysql). unfortunately don't find starting point begin. file mediawiki should altered? other suggestions? the main update done in includes/linksupdate.php . relevant hooks linksupdate , linksupdatecomplete . there seem 1 or 2 other places sortkey updated or record deleted. reads table seem done on place needed.

Defining a default controller for a folder in Codeigniter -

hey everyone, have codeigniter controllers set in folder called employees. issue don't seem know best way specify default controller if folder typed in url. instance, able type in: www.mysite.com/employees and have default personnel controller, instead of having type in: www.mysite.com/employees/personnel any ideas? thanks. how have specified in routes.php ? have tried with: $route['default_controller'] = "personnel";

custom action - Wix -- Backup the folder while installation -

i want backup folder before new files overwritten using wix control. example: installation folder "ifolder", upgraded product latest changes , created setup files. have install latest set in same "ifolder". case want take backup of "ifolder" before new files overwritten same folder @ time of installation. please add points in case. you can try use open source systemtools wix extension here: http://msiext.codeplex.com . an example, demo: <!-- copy files subdirectory, delete them on uninstall --> <appsecinc:copyfiles id="copyall" copyoninstall="yes" recurse="yes" source="[installlocation]" overwrite="yes" target="[installlocation]\copyofallfiles" wildcard="*.*" /> <appsecinc:deletefiles id="deleteall" deleteonuninstall="yes" recurse="yes" path="[installlocation]\copyofallfiles" wildcard="*.*" de

assignment from incompatiable pointer type C -

say want read in list of pages name of max 19 character, e.g. 4 (number of page) name1 name2 name3 name4 i trying use global 2d array store page number , page name, got error saying assignment incompatiable pointer type... thanks static int npages; static char** pagename; int main(void){ scanf(" %d", &npages); pagename = (char *)malloc(npages*sizeof(char)); for(int i=0; < npages ;i++){ pagename[i] = (char *)malloc(20*sizeof(char)); scanf(" %s", pagename[i]); } //free memory here of coz. return 0; } the problem lies right there: pagename = (char *)malloc(npages*sizeof(char)); pagename char ** , not char * . should read: pagename = malloc(npages*sizeof(char*)); // sizeof(char *), , no need cast edit: removed cast

c# - Global Class to access Variables -

we have global instance of class , access across application (in different forms etc) what different possiblities? (other static class). it sounds want singleton pattern. depending on application want careful though. 1 instance of it, , can cause unexpected behaviors multiple threads etc. (there other drawbacks too, main point have @ downsides of pattern also). c# patterns: http://www.dofactory.com/patterns/patterns.aspx

How to validate number in perl? -

i know there library that use scalar::util qw(looks_like_number); yet want using perl regular expression. , want work double numbers not integers. so want better this $var =~ /^[+-]?\d+$/ thanks. constructing single regular expression validate number difficult. there many criteria consider. perlfaq4 contains section "how determine whether scalar number/whole/integer/float? the code documentation shows following tests: if (/\d/) {print "has nondigits\n" } if (/^\d+$/) {print "is whole number\n" } if (/^-?\d+$/) {print "is integer\n" } if (/^[+-]?\d+$/) {print "is +/- integer\n" } if (/^-?\d+\.?\d*$/) {print "is real number\n" } if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {print "is decimal number\n"} if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([ee]([+-]?\d+))?$/) { print "is c float\

drop down menu - Why does an ASP.NET DropDownList control requires two clicks to expand in Internet Explorer -

i have asp.net dropdownlist control renders dropdown list (select html tag) on page. reason, when i'm in internet explorer, requires 2 clicks me open , see options, click end-user. works fine in google chrome, mozilla firefox , safari--i have click once see options selection. why not work correctly in ie? , more importantly, how can fix in ie? here code: <asp:dropdownlist id="ddlclientname" runat="server" enableviewstate="false" autopostback="true" class="inputfield" onfocus="change(this, event)" onblur="change(this, event)"> had remove hard-coded onfocus event. ie handles first click focus event, , second expand dropdown. guess known quirk ie along other 400+ quirks. i still trying figure out way change styles of dropdown on focus. depending on code put callback anonymous function, may still need click dropdown twice in ie. i've found can monkey other controls, inside functio

java - How can I send html/javascript values to sql and return it back to the same page in jsp? -

i started out html page. then, renamed file .jsp extension, using jsp accomplish particular task. which is: wish take value page on form, send sql used in clause, send data set same page. now, employ ajax, instead of submitting form. appreciate advice, step-by-step procedure, i'm bewildered @ least couple of items. 1) can write jsp code in same page? 2) can or should write sql inside jsp code? 3) should have page set jsp? i suppose i'm looking "hello world" explanation, i've worked non-java based languages in past. thank you. for quick , dirty, should @ using jstl sql tags. they're pretty easy use, actually, , eliminate of jdbc cruft if embedded java. this page decent little example covers of fundamentals, sql jstl.

Controlling the order of rails validations -

i have rails model has 7 numeric attributes filled in user via form. i need validate presence of each of these attributes easy using validates :attribute1, :presence => true validates :attribute2, :presence => true # , on through attributes however need run custom validator takes number of attributes , calculations them. if result of these calculations not within range model should declared invalid. on it's own, easy validate :calculations_ok? def calculations_ok? errors[:base] << "not within required range" unless within_required_range? end def within_required_range? # check calculations , return true or false here end however problem method "validate" gets run before method "validates". means if user leaves 1 of required fields blank, rails throws error when tries calculation blank attribute. so how can check presence of required attributes first? i'm not sure it's guaranteed order these validation

operator Overloading in C# -

class point { private int m_pointx; private int m_pointy; public point(int x, int y) { m_pointx = x; m_pointy = y; } public static point operator+(point point1, point point2) { point p = new point(); p.x = point1.x + point2.x; p.y = point1.y + point2.y; return p; } } example: point p1 = new point(10,20); point p2 = new point(30,40) p1+p2; // operator overloading is necessary declare operator overloading function static? reason behind this? if want overload + accept expression 2+p2, how this? yes. because aren't dealing instances operators. just change types want. here example #2 public static point operator+(int value, point point2) { // logic here. } you have other way parameters if want p2 + 2 work. see http://msdn.microsoft.com/en-us/library/8edha89s.aspx more information.

c# - Prevent namespaces of top Config from getting wiped out when loading and configuring other .config in Unity -

this specific , difficult situation explain, bear me. i have created unitycontainerextension responsible loading , configuring other .config files. for example, app.config file looks this: <configuration> <configsections> <section name="unity" type="microsoft.practices.unity.configuration.unityconfigurationsection, microsoft.practices.unity.configuration, version=2.0.414.0, culture=neutral, publickeytoken=31bf3856ad364e35" /> </configsections> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <assembly name="someassembly" /> <namespace name="someassembly.somenamespace" /> <container> <extension type="configsectionextension" /> <extension type="testextension" /> </container> </unity> </configuration> my first extension conf

php - Better way of error handling? -

what best way of error handling? came with: class test { public static function payment($orderid, $total) { if (empty($orderid) && empty($total)) { return array('status' => 'fail', 'error' => 'missing data'); } } } i heard try/exceptions how fit code? if provide example great! as mentioned, use exceptions . specific example, throw exception if condition fails. when envoke method can throw exception, wrap try/catch handling block. class test { public static function payment( $orderid, $total ) { if (empty( $orderid ) && empty( $total )) { throw new exception('missing data'); } } } try { test::payment("1", "2"); //should fine test::payment(); //should throw exception } catch (exception $e){ echo $e; //do other things if need }

c - print pointers of type (int *) in a coherent way -

i have code in c: int tab[10] = {3, 10, 5, 7, 9, 4, 9, 4, 6, 8, 0}; printf("(int*)&tab[0]=%p (int*)&tab[1]=%p (int*)&tab[1]-(int*)&tab[0]=%d\n", (int*)&tab[0], (int*)&tab[1], ((int*)&tab[1]) - ((int*)&tab[0])); and returns: (int*)&tab[0]=0xbf9775c0 (int*)&tab[1]=0xbf9775c4 (int*)&tab[1]-(int*)&tab[0]=1 what not understand why difference returned 1 instead of 4 @ end. tell me way print them (addresses , difference) in coherent way (int *)? because you're doing pointer arithmetic. , pointer arithmetic done in units of whatever pointer pointing (which in case 4, because sizeof(int) == 4 on system). if want know difference in raw addresses, either multiply result of subtraction sizeof(int) , or cast pointers char * before doing subtraction.

html - some simple question in php -

i have simple question. 1-how can change php pages in specify points? example if($flag) //go 1.php else // go 2.php what replace instead go ?.php 2- <form action="index.php" method="post"> <input type="button" name ="submit" value="comfirm"> if click on button index.php execute if there way in particular condition want index.php called for example have 2 text fields , button user must fill both of text , click on button until goes next pages if user fill 1 of text in must not go in second way index.php must not called. if ($flag) { header("location:1.php"); exit(0); } else { header("location:2.php"); exit(0); } for second question can either use javascript (not users have javascript enabled, it's not guaranteed work), , check value of fields, or hava serversite check , redirect user header , above.

android - Check the performance of the application? -

hey, finished code , works should i'm wondering since smartphones have limited battery, cpu .. how can check if application run on older phones? , how can check if app consumes phones battery? thanks the way know test app in phones. that said, can profile , make educated guesses based on how cpu-intensive app, how long running, if have services using cpu continuously, etc. there few things consider: the main battery drain screen. if keep kind of screen lock (even dim), destroy battery. any other lock (wifi, etc.), induce battery drain. use them? need them? release them they're not needed? do have hardware listeners (e.g., location, accelerometer), unregister them they're not needed take @ video: http://www.google.com/events/io/2009/sessions/codinglifebatterylife.html

ios - Multitasking in iphone? -

i developing game iphone application, has music player , and few animation. game interrupted text message or call terminated. should pause game until click cancel. while sound plays if receive call or message, audio player pause, after accept/decline call, doesn't play continue. how manage this? actualy have @ uiapplicationdelegate reference. there you'll see various methods called events beyond control occur (such phone call coming in, etc.) in case believe want override applicationwillresignactive , applicationdidbecomeactive methods handle pausing game, sounds, etc. , restoring them. update: found blog post helpful in understanding multitasking delegates: http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/

JavaScript RegEx Syntax -

i'm writing c# code parse javascript tokens, , knowledge of javascript not 100%. one thing threw me javascript regular expressions not enclosed in quotes. how parser detect when start , end? looks start / can contain character after that. note not asking syntax needed match characters, results google searches about. want know rules determining how know regular expression starts , ends. i consider following regexp reasonable approximation. /(\\/|[^/])+/([a-za-z])* the rules formally defined: regularexpressionliteral :: see 7.8.5 / regularexpressionbody / regularexpressionflags regularexpressionbody :: see 7.8.5 regularexpressionfirstchar regularexpressionchars regularexpressionchars :: see 7.8.5 [empty] regularexpressionchars regularexpressionchar regularexpressionfirstchar :: see 7.8.5 regularexpressionnonterminator not 1 of * or \ or / or [ regularexpressionbackslashsequence regularexpressionclass regularexp

Help With PHP Pagination Script For Flat File Database -

i have few questions regarding php pagination script flat file database found. have posted script below. <?php echo '<html><body>'; // data, flat file or other source $data = "item1|item2|item3|item4|item5|item6|item7|item8|item9|item10"; // put our data array $dataarray = explode('|', $data); // current page $currentpage = trim($_request[page]); // pagination settings $perpage = 3; $numpages = ceil(count($dataarray) / $perpage); if(!$currentpage || $currentpage > $numpages) $currentpage = 0; $start = $currentpage * $perpage; $end = ($currentpage * $perpage) + $perpage; // extract ones need foreach($dataarray $key => $val) { if($key >= $start && $key < $end) $pageddata[] = $dataarray[$key]; } foreach($pageddata $item) echo '<a href="/'. $item .'/index.php">'. $item .'</a><br>'; if($currentpage > 0 &&a