Posts

Showing posts from April, 2013

javascript - Preventing forge HttpRequests -

i've been searching throughout day find way figure out, without sucess , thought maybe here ? trying use secrete password in .js file can't write directly in file because see when accessing source code. e.g need send password using ajax page make sure httprequest website not forge httprequest . possible because i've tried else authentication forms didn't help. i'm using asp.net , httphandler page returns data . what can generate key valid set time using php so: $password = "some random string"; $key = md5($password . $_server['request_time']) . "|" . $_server['request_time']; this way know when key generated, , if it's been tampered because: function check($key) { list($hash, $timestamp) = explode("|", $key, 2); if ($hash !== md5($password . $key)) { throw new exception("naughty!"); } if ($timestamp < $_server['request_time'] < 60*60) { thr...

javascript - Using document.activeElement with an onChange event to validate a textbox only after textbox change is completed -

i have implemented version of code below on development system. function validatetextbox(textboxid) {   var textbox = document.getelementbyid(textboxid);   if(document.activeelement.id != textbox.id) {      do validation   } } the html similar to: <input type="text" id="validateme" onchange="validatetextbox('validateme');"/> the idea validation takes place after user has completed editing textbox , that, unlike onblur event, validation fires when value of textbox has changed. it seems work i'm leery of using without review , feedback. i haven't seen similar code examples. please give me thoughts on implementation , alternate ideas may have. thanks this fine solution. keep in mind onchange event typically fire when focus changes (ie. onblur) if want validation while user typing can use onkeydown/onkeyup/onkeypress that's quite ways harder. additionally can use this don't ...

asp.net - Jquery UI modal form example button click not working -

im using jqueryui modal form , since im new jquery figured first part integrate demo modal form application im working on , progress there. i have managed other simpler examples working, such basic modal popup box, when try work modal form popup nothing happens. the css / .js files in correct place , linked properly: <link type="text/css" href="../css/ui-lightness/jquery-ui-1.8.16.custom.css" rel="stylesheet" /> <script type="text/javascript" src="../js/jquery-1.6.4.min.js"></script> <script type="text/javascript" src="../js/jquery-ui-1.8.16.custom.min.js"></script> i took css provided , have placed within own css file know working correctly, can see style applied button etc. css is: /* ticket detail popup */ label, input { display:block; } input.text { margin-bottom:12px; width:95%; padding: .4em; } fieldset { padding:0; border:0; ...

ruby on rails - RoR Rake - database error about a gem -

i trying create db in ror application command: rake db:create and got error: could not find tzinfo-0.3.26 in of sources but when did "gem list" command, turned out had newer version of gem: tzinfo (0.3.27) what can sync gems more compatible? common problem? fyi using rvm manage gems. i did rvm install tzinfo-0.3.26 command , got output jruby-1.6.1-tzinfo - #fetching jruby-1.6.1-tzinfo - #extracting jruby-bin-1.6.1 /home/agenadinik/.rvm/src/jruby-1.6.1-tzinfo mv: cannot move `/home/agenadinik/.rvm/src/jruby-1.6.1-tzinfo' subdirectory of itself, `/home/agenadinik/.rvm/src/jruby-1.6.1-tzinfo/jruby-1.6.1-tzinfo' jruby-1.6.1-tzinfo - #extracted /home/agenadinik/.rvm/src/jruby-1.6.1-tzinfo building nailgun jruby-1.6.1-tzinfo - #installing /home/agenadinik/.rvm/rubies/jruby-1.6.1-tzinfo error: cannot switch 1.6.2 interpreter. jruby-1.6.1-tzinfo - #importing default gemsets (/home/agenadinik/.rvm/gemsets/) copying across included gems fetching: jruby-laun...

c# - Read (and write) Office document custom properties without automation -

i looking solution reading (and possibly writing) custom properties of office documents (both old , new formats) without resorting office automation. i have found dsofile.dll seems work old formats chokes on new ones "class not registered". kb remarks "office compatibility pack" needs installed work looking out-of-box solution. i not searching solution reads (and writes) custom properties without office installed. actually, considering office prerequisite. want solution not require office automation simple custom property handling. there "microsoft office metadata handler" windows explorer shell extension shows/manages custom properties office documents pretty way want it. dsofile.dll seem have 1 half of solution covering old office formats. dsofile use binary formats. for newer formats, can use xml (open xml sdk fine choice, can access docx/xlsx/pptx file formats system.io.packaging in .net if don't want heavy handed yet-anothe...

machine for developing/debugging android apps -

my current laptop has intel core2 duo p9500 @2.53ghz 4gb memory. running android emulator on eclipse quite pain (very slow). recommended/minimum system requirement android developers out there? right, not have stand-alone graphics card, has embeded intel graphics media accelerator gm45. a faster processor , hard-drive should help. honeycomb run slow on computer. but, no matter using, shrinking resolution of emulator/avd bit can help.

Python/Matplotlib - Colorbar Range and Display Values -

Image
when using matplotlib contour plot, i'm having trouble getting colorbar display want. i've read through numerous similar examples, have still not been able want. in image below, want 2 things changed. want minimum value , maximum values display on color bar (the max should 2.0 , min -0.1). these 2 values should @ edge of colorbar. also, want colorbar display value @ every color transition. example. in plot below, between 2.1 , 1.8, there color transition value isn't displayed. can please me? think may need use norm, hasn't worked me far. thanks, code: import numpy np import matplotlib.pyplot plt xi = np.array([0., 0.5, 1.0]) yi = np.array([0., 0.5, 1.0]) zi = np.array([[0., 1.0, 2.0], [0., 1.0, 2.0], [-0.1, 1.0, 2.0]]) plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') plt.contourf(xi, yi, zi, 15, cmap=plt.cm.jet) plt.colorbar() plt.show() if understand correctly want, think should it: import...

networking - Firefox add-on: hanging TCP connections -

i'm creating firefox add-on contains server listening tcp connections on 1 port. problem not close connection: after sending fin-ack, , receiving ack, tcp session left open if client not send in return fin-ack. only connections not closed completely. after while, many tc connections hanging, , firefox cannot open new file handle, or receive new connection. tcp localhost.localdomain:commtact-https->localhost.localdomain:46951 (close_wait) i not find way, preferably in add-on (but tried on client side) make sure tcp connections closed correctly. here server functionality looks in add-on: init_server: function(port) { server.result = {}; server.listener = { onsocketaccepted : function(serversocket, transport) { server.result.sout = transport.openoutputstream(0,0,0); var instream = transport.openinputstream(0,0,0); server.result.sin = components.classes["@mozilla.org/binaryinputstream;1"]. createinstance(components.interf...

.net - strange variable in lambda in foreach loop -

please refer question captured variable in loop in c# i want ask why variable behaves strange? static void main(string[] args) { int[] numbers = new int[] { 1, 2, 3 }; list<action> lst_want = new list<action>(); foreach (var currnum in numbers) { //--------- strange part ------------- int holder = currnum; lst_want.add(() => { console.writeline(holder); }); } foreach (var want in lst_want) want(); console.writeline("================================================"); list<action> lst_dont_want = new list<action>(); foreach (var currnum in numbers) { lst_dont_want.add(() => { console.writeline(currnum); }); } foreach (var dont_want in lst_dont_want) dont_want(); consol...

redirect - JavaScript window.location.replace works in Firefox but not IE or Chrome -

the following script works marvelously in firefox has no success @ in ie or chrome....i've been pounding head hours on stupidity....any appreciated. <script type="text/javascript"> window.onunload = function exitconfirm() { var answer = confirm("wait don't go! love you!"); if (answer) { if(!self.closed) { window.open("http://mykoolurl"); }else{ window.location.replace("http://mykoolurl"); } } } </script> the confirm works fine both page leave , broswer/page/tab close no matter selection choice in ie/chrome no redirect taking place. me understand. update more simple example using onbeforeunload: <body onbeforeunload=go();> function go() { if(confirm("go google")) { window.location.href = "http://www.google.com"; } } </body> this not work in ie/chrome/safari have used few differen...

php - Facebook Error validating access token: Session has expired at unix time -

i have integrated offline wall posting users of website have linked fb accounts there user details. have stored there fb-id, fb-access token in database , using php-sdk libraries had integrated feed wall posting in website. worked users getting messages on there facebook wall. today things went in vain throws various kinds of error. have been searching more documents can't find exact relevant solution issues. lines of code have used fb-wall posting $usid=$pageinfo['user']['id_facebook']; $accestoken=$pageinfo['user']["facebook_accesstoken"]; if($pageinfo['user']['user_fbtoken']=='1') $attachment = array( 'access_token' => $accestoken, 'message' => "mytaste || real restaurant reviews, share taste on mytaste", 'name' => "my favorite restaurant ".$business['name'].$business['location']['c...

Global Variables used across files in PHP -

i have come across situation need use queue , should accessible in pages . tried using global variables couldn't meet requirement. if isn't constant data, coud use session var some_page.php <?php session_start(); //never forget line when using $_session $_session['queue'] = "my queue value"; ?> other_page.php <?php session_start(); //never forget line when using $_session $queue = $_session['queue']; //use queue needs ?> if it's constant data, put value in php file, , include need. queue.php <?php $queue = "my queue value"; ?> some_file.php <?php require_once "queue.php"; echo $queue; ?> hope helps

algorithm - Solving a Fibonacci like recurrence in log n time -

finding nth term in fibonacci series f(n) = f(n-1) + f(n-2) can solved in o(n) time memoization. a more efficient way find nth power of matrix [ [1,1] , [1,0] ] using divide , conquer solve fibonacci in log n time. is there similar approach can followed f(n) = f(n-1) + f(n-x) + f(n-x+1) [ x constant ]. just storing previous x elements, can solved in o(n) time. is there better way solve recursion. as suspecting, work similar. use n-th power of x * x matrix |1 0 0 0 .... 1 1| |1 | 1 | 1 | 1 | 1 ................... ................... | ... 1 0| this easy understand if multiply matrix vector f(n-1), f(n-2), ... , f(n-x+1), f(n-x) which results in f(n), f(n-1), ... , f(n-x+1) matrix exponentiation can done in o(log(n)) time (when x considered constant). for fibonacci recurrence, there closed formula solution, see here http://en.wikipedia.org/wiki/fibonacci_number , binet's or moivre's formula.

jQuery events and iFrames -

i've made jquery scroll bar ( http://www.liime.net/projects/liimebar/demo_2.html ) i've realized doesn't work when mouse in iframe both mousemove events bound document when clicks scroll button , mousewheel event (mousewheel plugin) bound document. have ideas on how deal this? what use old opacity 0 trick. basically, wrap iframe inside container div, wrap div (or readonly textarea) opacity 0, wraps iframe. this used cause issues on ie, , overall prevent user interact iframe content, , i'm quite curious if better has come since. check this fiddle

vb.net - How to customize InnerException.Message for System.Data.UpdateException in ASP.NET -

first of taking time read through post. have question may newbie piece of cake some. i adding data database table using entity framework. when adding duplicate primary key exception in innerexception.message reads "violation of primary key constraint 'pk_studentid'. cannot insert duplicate key in object 'dbo.students'. statement has been terminated. " however, want rephrase error message end user, save exact message table name , column name logs later. essentially, want rephrase error message "you cannot have duplicate entry student identification number. please enter new value." how can this? i have tried inherit system.data.updateexception , put if check see innerexception.message reads, , change accordingly. did not work. thanks, i think want. try 'your code catch ex exception 'store ex.message want throw new exception("your custom message here.") ...

cakephp - Cake PHP Validation (+ preg_match()-warning) -

using cakephp 2.0 rc3. following validation in model: var $validate = array( 'loginname' => array( 'mincharactersrule' => array( 'rule' => array('minlength', 3), ), 'alphanumericrule' => array( 'rule' => 'alphanumeric', ), 'uniquerule' => array( 'rule' => 'isunique', ), 'on' => 'create', 'required' => true, 'allowempty' => false, ), 'password' => array( 'mincharactersrule' => array( 'rule' => array('minlength', 5), ), 'required' => true, 'allowempty' => false, ), 'email' => array( 'emailrule...

wpf - How to optimize style of Surface ListBox items? -

i'm having trouble performance 15 items in surfacelistbox. the listbox created source binding viewmodel , i'm using itemcontainerstyleselector, select 1 of 3 styles use. still have 8 controltemplates, since have 4 states dataitem can present, plus 4, when item selected. the styleselector pretty simple: public class taskstyleselector : styleselector { public style defaultstyle { get; set; } public style overduestyle { get; set; } public style presentstyle { get; set; } public style completedstyle { get; set; } public override style selectstyle(object item, dependencyobject container) { var t = item sekoia.karuna.public.models.tasks.task; if (t == null) return base.selectstyle(item, container); if (t.completed) return completedstyle; else if (t.intervalstarttime <= datetime.now && t.intervalendtime >= datetime.now) return presentstyle; else if (t.intervale...

wpf - What reasons could prevent explicit and implicit styles from applying? -

i have wpf test project use answering questions, somehow project got quite cluttered on time , stuff not work correctly anymore.this may not real problem since can throw away , create new 1 not quite viable solution in every case thought might interesting know can cause such behavior. especially surprising explicit styles not apply. e.g. have style <style x:key="enlargeimagestyle" targettype="{x:type image}"> <setter property="layouttransform"> <setter.value> <scaletransform scalex="1" scaley="{binding relativesource={relativesource self}, path=scalex}"/> </setter.value> </setter> <style.triggers> <trigger property="ismouseover" value="true"> <trigger.enteractions> <beginstoryboard> <storyboard> <doubleanimation to="2...

iphone - Get text between two tags and make another NSString from it -

i have html page html code (nsstring) this: <html> <p> texta </p> <p> textb </p> </html> <a> textc </a> and want text between tags , make nsstring. expected result code is: textatextb thank much. just search < sign, next > sign, , delete part. repeat until don't have signs left. replace regex <*> nothing.

Android EditContactActivity source -

android editcontactactivity contains functionality when + button pressed new field added listview , - button delete field. need exact functionality, not find in android source code. how extract particular functionality? , if can tell me how understand android source code. if remember correctly it's not listview @ actually, more like: <linearlayout> <scrollview> <linearlayout> editors go here </linearlayout> </scrollview> <linearlayout> buttons , stuff goes here </linearlayout> </linearlayout> basically they're adding , removing items in linearlayout @ right position. if want specifics (complete?) mirror of android repo @ github - contacts app, instance, here: https://github.com/android/platform_packages_apps_contacts

svn - What about the git storage system -

maybe stupid question, i'd raise here since it's not clear me: git commit file content snapshot relative svn commit delta storage systems, mean git needs more disk space svn ? thinks shall delta in reasonable. logically, git stores every file (actually, every object) in repository , identifies them sha1. can @ yourself, objects in directories in .git/objects identified first 2 characters of sha1. but git supports storing (and transferring) objects in called packfile. file contains objects compressed using zlib. can contain delta-compressed objects reference object in same packfile (it doesn't have previous version of same file). objects saved normal files compressed packfile when call git gc . happens automatically during of git operations produce “loose objects”. because of this, git working directory smaller svn working directory. great, considering git working dir contains history of repo. (svn working dir twice size of files in it. that's becaus...

jquery - Do something if screen width is less than 960 px -

how can make jquery if screen width less 960 pixels? code below fires 2nd alert, regardless of window size: if (screen.width < 960) { alert('less 960'); } else { alert('more 960'); } use jquery width of window. if ($(window).width() < 960) { alert('less 960'); } else { alert('more 960'); }

C++,Need help to understand some constructors and functions in a vector class using pointers -

greetings all; i have develop c++ class library comprising collection of numerical techniques scientific computing. library should implement vector class (using pointers) basic functionality stated in header file "vector.h". #ifndef vector_h #define vector_h template <class t> class cvector { private: int nn; //size of array t *v; //pointer array of data public: //default constractor cvector(); //zero based array cvector(int n); //initialize constant of value cvector(int n, const t &a); //initialize array cvector(int n, const t *a); //copy constractor cvector(const cvector &rhs); //assignment cvector & operator=(const cvector &rhs); //i'th element inline t & operator[](const int i); inline const t & operator[](const int i) const; inline int size() const; //resize (contents not preserved) void resize(int newn); //resize , assign constant v...

c# - What does "The non-generic type 'System.Web.UI.Pair' cannot be used with type arguments" mean? -

foreach (pair<pair<int, int>, cell> cell in sheet.cells) { dgvcells[cell.left.right, cell.left.left].value = cell.right.value; } i working on creating excel file within .net, using excel library i getting warning mentioned in title. ideas? just future reference, , understanding, error message: the non-generic type '' cannot used type arguments replaced class, indicates within code attempting make use of non- generic class in generic way. more using syntax incompatible type, in case <> generic braces on type "pair". to typically solve problem identify types use within file, use in generic way. (this should find them: ctrl + f > "someclass<") ensure type expected (f12 on type should take declaration) if type different expected type should make use of using alias point correct type namespace i.e. using pair = fully.qualified.namespace.of.pair; if type expected en...

playframework - Play Framework config value in view -

how can access value application.name conf/application.conf in view? you can use following code sample so: ${play.configuration['application.name']} also see http://groups.google.com/group/play-framework/browse_thread/thread/1412ca8fc3edd22f

ios - How do you know if a task executes in the background when your app sleeps? -

with objective c memory management, have general rule if create object of following techniques, need release object later. alloc new copy mutablecopy this rule simple remember. i'm looking analogous simple rule deciding whether background processing when app sleeps. such definitive list exist? nsurlrequest - if send request out hit home button right away, possible app still processes server response? timer - set off timer fire 1 minute now, hit home button before 1 minute elapse. timer still run, paused, or canceled? for loop - write loop million iterations. close app after it's done 600,000 iterations. happens rest of 400,000 iterations when app sleeps , when re-open app? and on... there's dozen other things i'm thinking whenever app sleeps. i'm worried because ever since started developing video camera app, battery life has been horrible (dropping 50% overnight). maybe it's coincidence or maybe camera still recording while app sleeping....

java - forward break label -

how can forward jumps this?? eclipse complaining label1 not found... thx public class foo { int xyz() { int b = 1; if (b == 0) { break label1; } // more code here label1: return 1; } } you trying use equivalent of goto in java. can't, , reason. abandon ship. labels included in java sole reason of choosing which loop or switch break out of, in case of nested loops (or switch statements). have no other purpose, , single purpose considered dangerously close goto.

android - setContentView problem -

i beginner in android beginer problems occured. create second activiy , second layout xml file named getnearest.xml. code section show file is setcontentview(r.layout.getnearest) but eclipse cannot find getnearest. shows .main. problem this? you need build @ least once have r.layout values updated when create new layout. make sure saved layout file , exists under res\layout folder.

java - Phonegap deviceready event -

i have question regarding event here, deviceready. document.addeventlistener('deviceready', function() { app.init(); }, false); it appears event fired every time device (i'm working on android 2.3) tilted side (so display changes wide). guess intended behavior, there way prevent it, application needs initialized once? here link solution how disable orientation change on android? by adding android:configchanges="keyboardhidden|orientation" to activity in androidmanifest.xml file, tells app handle configchanges yourself.

c++ - Programmatically Ignore Cout -

does know if there trick toggle cout << functions not print out visible output? trying hack code written me , other people put demo. rather not redirect output file , solution had measure of compatibility between windows , linux. in scenario have many many lines of code with various #defines controlling when methods produce debug output. want call like: cout.off(); driverforaffecta(); driverforaffectb(); cout.on(); printspecializeddebug(); exit(0); you can change cout's stream buffer. streambuf *old = cout.rdbuf(); cout.rdbuf(0); cout << "hidden text!\n"; cout.rdbuf(old); cout << "visible text!\n"; edit: thanks john flatness' comment can shorten code bit: streambuf *old = cout.rdbuf(0); cout << "hidden text!\n"; cout.rdbuf(old); cout << "visible text!\n";

ruby on rails 3 - How do I write a resource-less form with formtastic -

i'm having trouble creating following formtastic. it's simple form, it's not based on full resource, query string param i'd send. # index.html.haml ... = form_tag resources_path, :method => 'get' |f| = label_tag 'filter', 'filter' = text_field_tag(:filter, params[:filter]) = submit_tag('go', :name => nil) formtastic overkill here, it'd nice use consistent semantics if possible. how translate above formtastic syntax? did see these railscasts: http://railscasts.com/episodes/184-formtastic-part-1 http://railscasts.com/episodes/185-formtastic-part-2 https://github.com/justinfrench/formtastic/wiki/4-formtastic-options should this: = semantic_form_for @your_model |f| = f.inputs = f.buttons or this: = semantic_form_for @your_model |f| = f.input :filter = f.commit_button :label => "go" then run rails g formtastic/stylesheets , add them stylesheets / asset pipeline. you'...

.net - Private and Shared Assembly -

can strong named assembly (in gac) access private assembly (i.e. 1 not in gac)? by access mean, may using reflection invoke 1 of method. i have doubt because guess assembly put in gac strong named because of security reasons. , referring assembly outside gac seems me security breach...am right? please let me know i'm going wrong. yes, using reflection possible. if not in gac need file path load it.

How to import a library GMP into Sage/Python project -

i have installed gmp library, want import library sage project tried put : import libgmpxx.so.4 libgmpxx.so.4.path.append('usr/local/lib/') but does'nt work unfortunately, how can that. regards sage's integer class uses gmp (or mpir) automatically. if trying use gmp independently of sage, @ gmpy . disclaimer: i'm maintainer of gmpy.

php - Obtain text between p tags within only certain span IDs with DOMdocument or SimpleDOM? -

i trying pull plaintext between <p> tags if between span id='a' , span id='b'. simpledom seems work, , i've yet find way coax domdocument produce output @ all. maybe can you: $doc = new domdocument(); @$doc->loadhtml($html); $xpath = new domxpath($doc); $elements = $xpath->query("//*/p/span[@id='a']");

How to get parent color code (hexadecimal) using php -

i want parent color code php for example: input color code: #f5f5f5 , , child #ffffff ( #ffffff output) or #ff3535 child of #ff0000 i want #ffffff or #ff0000 or thing ... how done? thanks me

javascript - Dynamic Image filter using canvas and range input event -

i'm playing around image filters using canvas after reading post this post . basically, moves through pixels , update value something. what want adjust brightness of image using input range. i've attached onchange event handler, , call function update canvas every time user moves slider. obviously slows down page much, because when user moves slider 10 40, calls function 30 times!. tried using flag this: if (!myflag) { myflag = true; ...call function... myflag = false; } but that's not want, because want see in "real time" (like in photoshop) can give me hint solve this? may be, should use event, or perhaps different approach process imagedata. probably not work expect try adding timeout var myflag = false; var filtertimeout; slider.onchange = function() { if (!myflag) { myflag = true; cleartimeout(filtertimeout); filtertimeout = settimeout(function() { // apply filter hear myflag ...

silverlight - How to block input while WCF Asynchronous call runs? -

i'm working on application on windows phone, , using silverlight. have bugs user can press button twice, 2 wcf calls since action called 2 times. the obvious solution disable button until call completes i'm wondering if there's more global solution wouldn't have implement every action. application uses 50 wcf methods tedious implement every single action/every screens. there's situation users can click phone button while call running , start clicking on other buttons etc... anyone know clean solution this? simple solution: use boolean variable set true after first click , false when result server has arrived back. in click handler check value of variable, if true not call service again.

codeigniter - Get ID of newly created document -

i working mongodb , codeigniter (and alex bilbies mongodb library) , wondering. there way id of post create below directly after? $this->ci->mongo_db->insert('oauth_sessions', array('client_id' => $client_id, 'redirect_uri' => $redirect_uri, 'user_id' => $user_id, 'code' => $code, 'first_requested' => time(), 'last_updated' => time())); thankful input! you should able ci standard db function insert_id(). so directly after insert call do $ilastinsertedid=$this->ci->mongo_db->insert_id();

Customizing XML generation in Rails -

i new rails , have written few models. 1 of xml generated model looks this: <book> <read type="boolean">true</read> <title>julius caesar</title> <id type="integer">1</id> </book> the serialized xml want have more control on it. want generate same in different format. like: <book read="true" id="1"> <title>julius caesar</title> </book> how achieve this? have done research , found to_xml method should overridden. not sure how it. you can use custom ::builder::xmlmarkup this. however, the documentation active record serialization (see last code example) buggy. can this: class book < activerecord::base def to_xml(options = {}) # load builder of not loaded yet require 'builder' unless defined? ::builder # set indent 2 spaces options[:indent] ||= 2 # initialize builder xml = options[:builder] ||= ::bui...

directory - How to skip .hg / .git / .svn directories while recursing tree in python -

i have python script have been piecing (one of first python forays). the script recurses folder looking xcode project files; script works fine, adapt skip .svn (or .hg or .git) folders isn't trying modify source repositories. here script recursive search for root, dirnames, files in os.walk('.'): files = [f f in files if re.search("project\.pbxproj", f)] f in files: filename = os.path.join(root, f) print "adjusting basesdk %s" % (filename) ... how can exclude repository sub-trees? as s.lott says in comment, mentioned in documentation os.walk . following should work fine: for root, dirs, files in os.walk("."): if ".hg" in dirs: dirs.remove(".hg") f in files: print os.path.join(root, f)

exception handling - DeviceLostException during CTRL ALT DEL in Direct3D using C# -

i using microsoft.directx , microsoft.directx.direct3d references drawing on form. while running program , user presses ctrl alt del in windows xp , brings "windows security" form, when returning form, devicelostexception thrown , when trying handle exception there seems no way back. i have done little research matter , have tried several coding solutions. try { _d3ddevice.present(); } catch { devicelost = true; } if (devicelost) { attemptrecovery(); } this.invalidate(); readkeyboard(); base.onpaint(e); } private void attemptrecovery() { try { _d3ddevice.testcooperativelevel(); } catch (devicelostexception) { application.exit(); } catch (devicenotresetexception) { try { ...

PHP - How to check a subfolder for a single file? -

$code="524"; $filepath="/assets/$code/"; $file=""; if(@fopen($path,"r")){ // code // replace function here (ill this) } echo '<a href="link.php?go=$file">your colour is: </a>'; /assets/542 /assets/542_blush/ /assets/542_blush/542_blush.jpg at moment, code going 3 digits, have subfolder underscore , color , inside 1 file.. php has file_exists() function; if ( file_exists( '/assets/' . $code . '_blush/' . $code . '_blush.jpg' ) ) { // ... }

android - ListView .putExtra from DB Column -

i trying data db column contains url link; column name 'goto' w/in db. need pass onitemclick intent in listview load webpage new/next activity. i don't know how function. if can please show code modifications explanation, helpful me learning. thnx! revised: i getting data passed method returning wrong row id. revised below activity. plz. thnx within activities .oncreate (revised): final listview lv = getlistview(); lv.settextfilterenabled(true); lv.setonitemclicklistener(new onitemclicklistener() { // @override public void onitemclick(adapterview<?> a, view v, int position,long id) { object o = lv.getselecteditem(); //adapter_ac fullobject = (adapter_ac)o; string url = "gotourl"; if(v != null) { textview tv = (textview)lv.findviewbyid(r.id.dummy); url = (string) tv.gettag(); } toast.maketext(list_ac.this, ...

jQuery Ajax load and getScript -

i'm trying set site content in main area loaded via javascript (some pages take while render). however, i've run bit of logical problem when using jquery.load(), jquery.getscript , jquery.ajax(). i need able load javascript files via getscript can use these functions etc inside loaded content. index.php - main file being displayed (also contains #loading) js/script.js - file containing load code js/*.js - several javascript files need able use inside #maincontent after load load.php - file being loaded #maincontent script.js: $(document).ready(function() { $('#loading').fadein('fast'); $('#maincontent').load('load.php', function() { $('#loading').fadeout('fast'); $('#maincontent').fadein('slow'); }); $('#navigation li a').click(function() { $('#maincontent').fadeout('fast'); $.getscript('js/jquery.contextmenu-1.01.js'); $.getscript('js/jquer...

ruby on rails - Why does limit still return the entire document set in Mongoid? -

this seems causing queries slow, , i'm confused why returning entries of document. >> product.skip(0).limit(20).count => 3826 thats behaviour of count(), returns count of records query touched you need use size() count current set.

foreign keys - Entity framework code first - association on "polymorphic" columns -

i have 3 tables: 1. invoice invoiceid int primary key 2. order orderid int primary key 3. transaction transactionid int primary key source int category string on table "transaction", source (unfortunately) behaving "polymorphic"(??) foreign key (there must actual term - sorry ignorance) depending on category column it'll contain id of invoice or order. however there's no actual foreign key. using ef 4.1 code first, has idea how create proper associations? help appreciated! thanks solution uh... embarrassment kicking in... can map same way regardless of actual db foreign key. i having problems while trying wasn't related this. had computation properties didn't ask context ignore generating wrong queries. you should create 2 nullable fks instead of weak reference that.

What is the benefit of using int16? instead of int16 in a .net variable declaration? -

possible duplicate: c# - basic question: '?' ? what benefit of using int16? instead of using int16 in .net variable declaration ? dim int16? dim int16 question mark indicates nullable types: http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.100%29.aspx

How do I find the index of an object from a list in VB.NET? -

say have list, , have object. how find index of object in list? you can use findindex find index of object in generic list: flexible method index of object. dim list new list(of object) const myapple = "apple111" = 0 1000 list.add("apple" & i) next dim indexofmyapple = list.findindex(function(apple) (myapple.equals(apple))) but indexof method simplier , more straightforward if want find object in list defaultequalitycomparer : dim indexofmyapple = list.indexof(myapple) you can use indexof if don't know type is, .net use equals determine if 2 objects equal(should overridden not compare references).

mysql - phpMyAdmin, an 'if'-esque type statement for 2 foreign key fields in 1 table -

as title suggests, have difficulty explaining this. :p i have 3 tables in phpmyadmin setup. within 1 of tables, contains 2 foreign keys. e.g foo_id , bar_id. these have been indexed , displaying fields names. is possible constrain can selected in bar_id after first selecting foo_id? if x=1 print = 6-10 else print 1-10 thanks in advance. i don't think can constraint, if wanted achieve trigger. however kind of validation logic in app layer, unless people going using database directly.

java - Why this errors appear in my console? -

Image
i noticed rare error messages on browser console, don't know reason. use primefaces gadgets in app, works fine, when navigate 1 page keep see in console: i don't know wrong. want mention pages use 1 same template, has navigation gadget see in image above. in template @ head tag added scripts: <script type="text/javascript" src="/primefaces_resource/2.1/yui/utilities/utilities.js"></script> <script type="text/javascript" src="/primefaces_resource/2.1/yui/datasource/datasource-min.js"></script> <script type="text/javascript" src="/primefaces_resource/2.1/primefaces/paginator/paginator.js"></script> <script type="text/javascript" src="/primefaces_resource/2.1/yui/datatable/datatable-min.js"></script> <script type="text/javascript" src="/pr...

.net - XamlReader.Parse throws the "Invalid character in the given encoding" -

i have problem following code: using (streamreader reader = new streamreader(stream, encoding.utf8)) { var content = reader.readtoend(); parsercontext context = new parsercontext() { baseuri = new uri(configuration.skinsfolder) //,xmllang = "utf-8" // have tried parameter , without }; var result = xamlreader.parse(content, context); return result; } the corresponding xaml, problem appears: ... <textblock>русская надпись</textblock> <textblock text="קח מספר" /> ... during parsing xaml exception: invalid character in given encoding. line 76, position 167. @ system.windows.markup.xamlreaderhelper.rethrowasparseexception(string keystring, int32 linenumber, int32 lineposition, exception innerexception) @ system.windows.markup.xamlreaderhelper.read(xamlnode& xamlnode) @ system.windows.markup.xamlparser.readxaml(boolean singlerecordmode) @ system.windows.markup.xamlparser._parse() @ ...

wpf - Is there a way to get a callback when a control (eg: Button) completes execution of ICommand? -

i have user control takes exposes icommand dependency properties, allowing vm specify command. is there way can attach handler (callback) in buttons of control (which execute icommand) control knows when command execution completed? thanks interest. you can create abstract callbackablecommand raise callback method. abstract class callbackablecommand : icommand { private iinputelement getraisedelement() { return keyboard.focusedelement; } public void execute(object parameter) { executeimpl(parameter); var element = getraisedelement(); if(element == null) return; //var ci = typeof(executedroutedeventargs).getconstructors(bindingflags.nonpublic | bindingflags.instance)[0]; //var routedeventargs = (routedeventargs)ci.invoke(new object[] { this, parameter }); var routedeventargs = new routedeventargs(); //routedeventargs.routedevent = commandmanager.executedevent; routedeventargs.routedeve...

java - Why is this thread allowing another one to access its synchronized method? -

i have following codes. expected 1 thread execute synchronized method , allow 1 access same method. however, not case. public class threads { /** * @param args */ public static void main(string[] args) { //thread th = new threads(); thread th = new thread (new thread1 ()); th.start(); thread th1 = new thread (new thread1 ()); th1.start(); } } class thread1 implements runnable{ string name = "vimal"; public void run() { system.out.println("runnable "+this.name); setname("manish"); } public synchronized void setname(string name){ try { system.out.println("thread "+thread.currentthread().getname()); wait(1000); this.name = name; system.out.println("name "+this.name); } catch (interruptedexception e) { // todo auto-generated catch block e.printsta...

c++ - Activate previous process on Mac -

is possible determine previous active process activate it? mac os x / c++ / carbon. getnextprocess() not refer z-order of processes, need real previous. the original task bring user work when closes info window. window of app gets focus, if any, or there no window focus. unusable. update. i'm using following workaround: 500ms timer watches getfrontprocess() not equal getcurrentprocess() . calling setforegroundprocess() last stored serial number. you can zorder of processes this place. last process should 1 looking for. or change code read in reverse.

oracle - how to write a java stored procedure? -

how write java stored procedure in oracle? advantages of java stored procedures on pl/sql stored procedures? thanks a quick google search turns page on using java stored procedures written oracle themselves

flash - ActionScript - textfield that shrinks font size -

how can create in actionscript singleline textfield automatically shrinks textsize whatever string shall displayed fits within size of textfield? thanks! i'd create function tries various font sizes until textfield has required width. this: public function shrink(textfield, requiredwidth) { textfield.autosize = "left" var tf:* = textfield.gettextformat(); tf.size = 50; textfield.settextformat(tf); while (textfield.width > requiredwidth) { tf.size--; textfield.settextformat(tf); } }

rails 3: format.csv gives "no template error" but format.json needs no template -

how come works render :json no template, not render :csv? in datapoints_controller's index method: respond_to |format| format.json { render :json => @goal.datapoints.all } format.csv { render :csv => @goal.datapoints.all } end pointing browser /datapoints.json renders collection json string on screen. pointing /datapoints.csv gives error: template missing: {:locale=>[:en, :en], :formats=>[:csv], :handlers=>[:rhtml, :rxml, :erb, :builder, :rjs]} an instance of datapoint responds to_csv, if manually map csv format , render text gives template missing error, so, e.g. tried this: format.csv { render @goal.datapoints.map{|d| d.to_csv }.join "\n" } rails comes renderers bunch of formats, including json, not csv. here's specified in rails source (look towards bottom series of add calls). it's pretty easy create own though. put initialiser (this pretty copied xml renderer above link, xml replac...

Moving files by starting letter in powershell, python or other scripting language running windows -

i need script can recursively traverse c:\somedir\ , move files c:\someotherdir\x\ - x starting letter of file. can help? ended one: import os shutil import copy2 import uuid import random source = ".\\pictures\\" dest = ".\\pictures_ordered\\" path, dirs, files in os.walk(source): f in files: print(f) starting_letter = f[0].upper() source_path = os.path.join(path, f) dest_path = os.path.join(dest, starting_letter) if not os.path.isdir(dest_path): os.makedirs(dest_path) dest_fullfile = os.path.join(dest_path, f) if os.path.exists(dest_fullfile): periodindex = source_path.rfind(".") renamed_soruce_path = source_path[:periodindex] + "_" + str(random.randint(100000, 999999)) + source_path[periodindex:] os.rename(source_path, renamed_soruce_path) copy2(renamed_soruce_path, dest_path) ...

winforms - Abstract Windows.Forms.Panel possible in C#? -

i trying create program has multiple layers of controls drawing on top of each other. way i'm doing have windows.forms.panel container panels doing actual drawing (this way can layer them). for panels doing drawing have abstract class inherits windows.forms.panel (call abstractpanel) have set docking style "fill". overrides onpaint function in calls abstract function override in children. the problem have when add control inherits abstractpanel container isn't showing (the onpaint function isn't being called). any suggestions? am thinking java perspective , need make abstractpanel not abstract? i've had similar issue visual studio winforms designer: if form inherits abstract class, doesn't shown in designer @ all. don't know why, reason windows forms doesn't "like" abstract classes. try removing abstract keyword, won't change functionality if do.

wpf - How to make image not stretch? -

[imgur deleted image] the icon on left result of code: <button height="23" horizontalalignment="left" margin="12,276,0,0" name="button1" verticalalignment="top" width="75"> <stackpanel orientation="horizontal"> <image source="resources/add.png" stretch="none" /> <textblock margin="5,0,0,0" text="add" /> </stackpanel> </button> the 1 on right original image placed beside using photoshop. appears 1 added via code stretched pixel causing distortion. how prevent that? stretch="none" should that. if there difference in how image displayed may due pixels ending "on edge". you try setting snapstodevicepixels ="true" avoid this.

How to connect "Tally ODBC" through python? -

i using tally.erp9, haven't found tally odbc connection on net. want python script connect tally database. can links , python scripts connect tally database using tally odbc? since supports odbc, might try pyodbc: http://pyodbc.sourceforge.net/

flash - Mobile/IOS app in Flex Builder 3? -

is possible publish mobile (specifically ios) app using flex builder 3, or available on flash builder 4.5 , later? mobile support available in flash builder 4.5 , later. can use free command line tools create mobile applications; recommend upgrade tooling because save lot of headaches. although possible, not sure recommend trying publish flex 3 based app ios or mobile platform. rewriting app use spark components going give more optimized performance.

c - Program runs then says it has stopped working. Debugging issues -

i writing code in c using codeblocks take schedule , tells if double booked on item. the file setup like: 2 2 0 1 5 1 8 12 where 1st number how many schedules there , second number how many scheduled items in schedule. the next few lines read 0 sunday, 1 monday , forth , hours day schedule full, start time end time. my code is: //10/14/11 //this code functions let user know if schedule conflicts exist in amount of schedules. #include <stdio.h> int main() { int hours_week[168]; int num_schedules; int num_items; int i; int j; int k; int w; file* ifp; int day; int start; int end; int schedule; int booked; int index; //initialize array setting each spot equal zero. (w=0; w<168; w++){ hours_week[w] = 0; } //read in file schedule.txt ifp = fopen("schedule.txt","r"); //read in number of schedules fscanf(ifp, "%d", &num_schedules); ...

c# - Should placeholder text be used for EventArgs properties if the value is not available? -

let's had event messagetransferfailed . event takes eventargs argument specifies local ip , remote ip. now let's assume message transfer failed because corresponding tcpclient disposed , result, can no longer access client.localendpoint , client.remoteendpoint . now have (?) specify sort of placeholder ips event args event invocation because cannot access them tcpclient. guideline placeholder text use in circumstance? should both properties ( localip , remoteip ) contain empty strings? sort sort of meaningful message "unknown" ? sentence indicating error occurred clients can understand happened? what best practice in situation? set localip , remoteip null , add new property specify whether or not result succeeded