Posts

Showing posts from June, 2010

c - Zero a large memory mapping with `madvise` -

i have following problem: i allocate large chunk of memory (multiple gib) via mmap map_anonymous . chunk holds large hash map needs zeroed every , then. not entire mapping may used in each round (not every page faulted in), memset not idea - takes long. what best strategy quickly? will madvise(ptr, length, madv_dontneed); guarantee me subsequent accesses provide new empty pages? from linux man madvise page: this call not influence semantics of application (except in case of madv_dontneed ), may influence performance. kernel free ignore advice. ... madv_dontneed subsequent accesses of pages in range succeed, result either in reloading of memory contents underlying mapped file (see mmap(2)) or zero-fill-on-demand pages mappings without underlying file. ... the current linux implementation (2.4.0) views system call more command advice ... or have munmap , remap region anew? it has work on linux , ideally have same behaviour on os

javascript - JS: displaying an infinitely long coordinating system (grid) -

i display infinitely long coordinating system/grid (x , y axes), contains endless amount of square (something divs), using javascript. don't have idea start. seems me hard problem solve. there many factors of don't have idea build them, such as: structuring them in html element tree using right elements (probably svg elements) giving grid fluid scroll coordinating loading of each element (if has displayed) i sure there javascript libraries, can me doing it, don't know of these. what way start with? here concept of grid: (y axis) ^ | | | | |--+------+------+--- | e| squre| squre| sq | | | | |--+------+------+--- | e| squre| squre| sq | | | | |--+------+------+--- | e| squre| squre| sq +--------------------> (x axis) while in comments said similar graphing, give kineticjs peek. uses canvas's , bit of overkill attempting it's great resource has many uses since you've requested grid, here question on

c# - Windows 8 style charmbar in WPF? -

Image
i want create wpf application docked on right side of screen. want act windows 8 charms bar. the bar shouldn't visibile on default when mouse of user comes right side of screen. how can achieve ? i want run application on vista/windows 7 example of charmbar : •you can place window of application right of screen. need handle events when mouse enters (mouseenter) , leaves (mouseleave) form move form , down. •you can use background thread call getcursorpos method @ set interval (i.e. each 500ms) second check mouse is. see link more information , sample code: http://www.pinvoke.net/default.aspx/user32.getcursorpos . (if need check mouse position, can use timer simplify application.) from: create dock application using c# , wpf to sliding effect follow how show window sliding effect right left in wpf and position window: how set location of wpf window bottom right corner of desktop? moral of story stop asking questions have been asked many time.

Prolog: store solutions in a list -

this simple question ;) fact(a). fact(b). test(x):-fact(x). the solutions x=a; x=b. ok i'm trying create: test(x,l):-fact(x), ??? returns l=[a,b] can me? thanks. use findall/3 aggregate solutions: test(l):- findall(x, fact(x), l).

java - MapResult with CypherDSL -

i have query, built cypher-dsl (b/c match -clause dynamic) , result-set contains nodes represented @nodeentity annotated pojos (amongst other columns). my question is: there way have result of dynamic (non-annotated) query, wrapped @mapresult (or regular map nodeentities values)? the following approach doesn't seem work, because inferred type of graphrepository has either node- or relationshipentity: @nodeentity public class customer { @graphid long id; ... } @mapresult public interface customerqueryresult { @resultcolumn("cust") customer getcustomer(); @resultcolumn("val1") int getval1(); ... } public interface customerqueryrepository extends graphrepository<customerqueryresult> { } @service public class searchservice { private customerqueryrepository repo; ... @inject public searchservice(customerqueryrepository repo, ...) { this.repo = repo; ... } public iterable&l

immutability - Is using a StringBuilder a right thing to do in F#? -

stringbuiler mutable object, f# encourages employing immutability as possible. 1 should use transformation rather mutation. apply stringbuilder when comes building string in f#? there f# immutable alternative it? if so, alternative efficient? a snippet i think using stringbuilder in f# fine - fact sb.append returns current instance of stringbuilder means can used fold function. though still imperative (the object mutated), fits reasonably functional style when not expose references stringbuilder . but equally, can construct list of strings , concatenate them using string.concat - efficient using stringbuilder (it slower, not - , faster concatenating strings using + ) so, lists give similar performance, immutable (and work concurrency etc.) - fit if building string algorithmically, because can append strings front of list - efficient operation on lists (and reverse string). also, using list expressions gives convenient syntax: // concatenating strings using +

javascript - In Safari on iPad is there a way to stop the page rubber banding BUT still allow overflows too scroll? -

there's lot of snippets stop rubber-banding on ipad, 1 below: document.body.addeventlistener('touchmove',function(event){ event.preventdefault(); },false); however has unwanted effect of preventing divs overflows on them scrolling too? is there way top page (body) rubber-banding while still allowing overflowed-scrolled divs so? the rubber-banding of entire page seems happen when user scrolling bottom or top of div. code i've written checks see if user indeed @ 1 of extremes , if prevents scrolling action happening in directions. elem.bind("touchstart", function( e ) { xstart = e.originalevent.changedtouches[0].screenx; ystart = e.originalevent.changedtouches[0].screeny; }); elem.bind("touchmove", function( e ) { var xmovement = e.originalevent.changedtouches[0].screenx - xstart; var ymovement = e.originalevent.changedtouches[0].screeny - ystart; if( elem.scrolltop() == (elem[0].scrollheight - elem[0].client

ios - Should sdk = deployment target? -

and happen if it's not case. this may seem easy question. say base sdk 5. why can't run on ios 7? what? ios 7 can't run stuff built base sdk 5? so true base sdk must bigger or equal deployment target? if why? what plus , minus if 2 numbers different? i looking answers answer: 1. bad things happen if sdk > deployment target 2. bad things happen if deployment target < sdk from apple choose deployment target. identifies earliest os version on software can run . default, xcode sets version of os corresponding base sdk version , later. and choose base sdk. your software can use features available in os versions , including 1 corresponding base sdk . default , xcode sets newest os supported xcode. your xcode have base sdk option of whichever latest ios version knows (6.1 xcode 4.5, 7 xcode 5). lets use newest features. say base sdk 5. why can't run on ios 7? what? ios 7 can't run stuff built base sdk 5? nonsense, can ru

Failure on build with Gradle on command line with an android studio project : Xlint error -

when try build android project gradle command : > gradlew clean build assemblerelease it gives me error : note: input files use or override deprecated api. note: recompile -xlint:deprecation details. note: input files use unchecked or unsafe operations. note: recompile -xlint:unchecked details. i can build project , make apk in studio. is there way configure gradle make compilation ignoring xlint notifications ? or, can use other parameters, make release command-line gradle/gradlew ? it's nice warning not error, see complete lint report can add these lines build.gradle: allprojects { tasks.withtype(javacompile) { options.compilerargs << "-xlint:deprecation" } } if want rid of warnings: don't use deprecated api use @suppresswarnings("deprecation")

php - Regexp OR operator -

i'm using .htaccess generate nice looking links, , need include or on slash so example domain.com/page/12/a/ , domain.com/page/12/a work what i've tried: rewriterule ^page/([^/]*)/([^/]*)(/?)([^/]*) index.php?do=atoz&category=$1&letter=$2&type=$3 [l] in case simple quantifier ? zero or one should work. ^page/([^/]*)/([^/]*)(?:/([^/]*))? ## # edit: might non-matching group can quantify optional. starts ?: .

ruby - Typing "guard" gives an exception -

i'm trying learn guard using jeffrey way's book, having issues when guard . although followed guides without making mistake. c:\users\imaqtpie\desktop\laraveltestingdecoded\chapter3>guard 18:41:48 - info - guard using terminaltitle send notifications. 18:41:48 - info - running tests php fatal error: call undefined method phpunit_framework_testresult::allcompletlyimplemented() in c:\railsinstaller\ruby1.9.3\lib\ruby\gems\1.9.1\gems\guard-phpunit-0.1.4\lib\guard\phpunit\formatters\phpunit-progress\phpunit\extensions\progress\resultprinter.php on line 250 php stack trace: php 1. {main}() c:\users\imaqtpie\desktop\laraveltestingdecoded\chapter3\vendor\phpunit\phpunit\composer\bin\phpunit:0 php 2. phpunit_textui_command::main() c:\users\imaqtpie\desktop\laraveltestingdecoded\chapter3\vendor\phpunit\phpunit\composer\bin\phpunit:63 php 3. phpunit_textui_command->run() c:\users\imaqtpie\desktop\laraveltestingdecoded\chapter3\vendor\phpunit\phpunit\phpunit\textui\

python - GTK3 multiple UI files -

i tying make login form using python , gtk3 of anjuta. far, have ui file login section, , form makes http request. class looks this: class gui: def __init__(self): self.builder = gtk.builder() self.builder.add_from_file(ui_file) self.builder.connect_signals(self) window = self.builder.get_object('window') window.set_title("login") window.show_all() self.username = '' self.password = '' when fill in correct data, http request successful , can see response in console. want clear current window (ui file) , load new 1 in place. is, without closing actual window , opening new one. how do that? let's have ui file <?xml version="1.0" encoding="utf-8"?> <!-- generated glade 3.15.3 on tue sep 17 10:11:35 2013 --> <interface> <!-- interface-requires gtk+ 3.10 --> <object class="gtkgrid" id=&

Cannot install vim into msys -

i installed msys on c:\msys drive. downloaded vim extensions vim-7.3-2-msys-1.0.16-bin.tar.lzma here , copied c:\msys . after invoking sh , typing vim or vi inside msys shell sh , message box pops , says. have posted screenshot here . me fix issue. don need install vim separately. need working inside msys . the program cant start because msys-iconv-2.dll missing computer. try re installing program fix it.

** Restricted Text ** when Reviewing Execution Plan in SQL Server Management Studio -

Image
i'm reviewing execution plan see why stored procedure running slowly. in execution plan window instead of useful missing indexes text ** restricted text ** instead. this has perked curiosity i've not seen before , can't find reference googling or indeed searching so. could please explain telling me and, if possible, how un-restrict text - i'm guessing ssms trying tell me whatever trying tell me quite verbose , being replaced text instead. ? there few cases client tools obfuscate query text, in different tools, depending on version: the use of sp_password the creation of login with password the with encryption option certain encryption / decryption functions with credit @lamak, see this , try this: create login lamak password = 'w0w, l@m@k $m@rt!'; depending on version, ssms either give plan ** restricted text ** in place of actual command wrote, or not give plan @ all. think modern versions don't bother exposing plans ddl

php - twitter like url and htaccess -

below .htaccess: <ifmodule mod_rewrite.c> rewriteengine on rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^(.*)$ index.php?url=$1 rewriterule ^(.*)/$ index.php?url=$1 </ifmodule> i trying fancy twitter url. www.mywebsite.com/home rather www.mywebsite.com/home.php in index.php code this: <?php $key=$_get['url']; if($key=='index') { include('welcome.php'); // welcome page } else if($key=='login') { include('login.php'); // login page } else { include('index.php'); // go index.php } ?> this keeps giving me invalid 404 error. , when output: echo $key shows this: index.php not index what doing wrong? that's worst way make url friendly because if have 1000 pages you'll have create "case" him in "switch". , if "require_once" passing parameter $key, vulnerability, known lfi ( local file inclusion ). what recommend stu

java - Why does my Application crash at startup? -

i can't change progress bar in webview application circle.the application crashes @ startup..here's code @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); webview = (webview) findviewbyid(r.id.webview); websettings websettings = webview.getsettings(); websettings.setjavascriptenabled(true); getwindow().requestfeature(window.feature_indeterminate_progress); // request progress circle setprogressbarindeterminatevisibility(true); // show progress circle // webview.setwebviewclient(new webviewclient()); final activity activity = this; webview.setwebchromeclient(new webchromeclient(){ public void onprogresschanged(webview view, int progress) { activity.settitle("loading..."); activity.setprogress(progress * 100); if(progress ==

android - parseSdkContent failed error in eclipse -

when opening eclipse opens, shows 1 error i.e android sdk content loader has encountered problem.parsesdkcontent failed when click on details button, shows me parsesdkcontent failed java.lang.nullpointeexception . and when tried create avd shows error location of android sdk has not been setup in preferences while have set path in preferences. please me. because of issue work pending. it's quite late answer had similar problem... you can refer android l parsesdkcontent failed not initialize class android.graphics.typeface

java - Why can't I access the value of the field in jsp (it returns null)? -

i've following javascript function: function confirmaenviar() { document.getelementbyid("data").value =clave2.value; alert(document.getelementbyid("data").value); more code here where check i'm able asign new value tu data; data being defined this: <form action="client.json" method="post" name="usuario" id="usuario"> more code here <input type="hidden" name="data" id="data" value="prueba" /> more code here </form> later on jsp part: <div><a href="javascript:void();" onclick=" javascript:if(confirmaenviar())$('#usuario').submit(); <% <% more code here string str= request.getparameter("data"); str null, can point me out do? thanks. i think have change attribute action="client.json" action="client.jsp"

php - Uncaught OAuthException: (#200) Error on Facebook -

i want post on facebook wall using access token when use facebook login works when other user use, doesnt work. for posting use account , authorize user login after getting access token using access token post on facebook wall. it not working other user's login, please help. code $facebook = new facebook(array( 'appid' => $conf->get("facebook_api_id"), 'secret' => $conf->get("facebook_secret_id")) ); $user = $facebook->getuser(); $params = array( 'description' => $campaign['message'], 'message' => $campaign['message'], 'picture' => $campaign['image_path'], 'created_time' => strtotime($campaign['post_datetime'])); $facebook->setaccesstoken($campaign['access_token']); $uid = $facebook->getuser(); $

ruby on rails + best_in_place + datatables + haml -

datatables editing example (using best_in_place) this example shows how create editable tables using datatables.net , best_in_place. currently datatables.net has example using jeditables jquery plugin. gemfile: gem "best_in_place" app/assets/javascripts/application.js: //= require jquery //= require jquery-ui //= require jquery.purr //= require best_in_place app/views/schedules/index.html.haml: %table - @schedules.each |s| %tr %td= best_in_place s, :name :javascript $(document).ready(function() { /* activating best in place */ jquery(".best_in_place").best_in_place(); });

Android- Simple bookmarks from a webview -

i trying implement bookmark system app uses webview load 1 of several html pages spinner. ideally, viewed webpage in webview saved bookmark database after user clicks button in menu. i know need database , through other questions , answers on stackoverflow saw google has tutorial shows how done. i tried adapt notepad tutorial google, unable implement successfully. converting between strings , uris didn't seem go through correctly. has encountered way make simple bookmark system webviews? or tips on using notepad tutorial ?

xcode - iOS - Autolayout not working for main UIView - (screenshots inside) -

i seem having problems getting main uiview in view controller stay same size when going portrait mode. screenshots pretty tell whole story. ipad , ios 6.1, xcode 4.6. landscape portrait and here screenshot of constraints within xcode it looks textviews , button within view stays in same position , size uiview (which subview view controllers view) not want keep same width , height. i load view programmatically via delegate couple of reasons thats fyi - trying give info possible. //set starting root view controller login screen uistoryboard *storyboard = [uistoryboard storyboardwithname:@"mainstoryboard" bundle:nil]; demoviewcontroller *loginvc = (demoviewcontroller *)[storyboard instantiateviewcontrollerwithidentifier:@"loginvc"]; self.window.rootviewcontroller = loginvc; [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(changerootvcsplit:) name:@"changerootvcsplitnotification" object:nil]; i learnin

c++ - What algorithm should I use to find the minimum flow on a digraph where there are lower bounds but not upper bounds on flow? -

Image
what algorithm should use find minimum flow on digraph there lower bounds, not upper bounds on flow? such simple example: in literature minimum cost flow problem. in case cost same nonzero lower bound on flow required on each edge worded question above. in literature question be: best algorithm finding minimum cost flow of single-source/single-sink directed acyclic graph in each edge has infinite capacity, non-zero lower bound on flow, , cost equal lower bound on flow. from research seems main way people deal kind of minimum cost of kind of network set problem lp-type problem , solve way. intuition, however, not having upper bounds on flow ,i.e. having edges infinite capacites, makes problem easier, wondering if there algorithm targeting case using more "graphy" techniques simplex method et. al. i mean, if costs , lower bounds 1 in above... looking flow covers edges, obeys flow rules, , isn't pushing flow through path s t. feels shouldn't require lp solve

mysql - Pass value between different pages (form) with PHP -

i trying bring value form in page1.php (form add data db) page2.php (form add img db). read whole bunch of pages how still can't figure out. <form name="formbrokertour" class="login-form-addproperty" method="post" action="insertpropertyinfowithgeocode.php" onsubmit="return validateform()"> and need add several fields, address, city, zip code state. here 1 out of 4: <td width="125" class="formlable">address</td> <td width="269" class="formsquare"> <input type="text" class="general_input" name="address" id="nametext" width="269" > </td> page2.php (relevant part) - see, if write address, address addded in database, don't need worry sql being wrong. if try pass info page 1 page 2 either session (since have username in place add info in database) or post/get, address not added. interes

android - Clarification needed for HTTP redirect -

could me out this: i getting 200(success) instead of 302(re-direct) http response, getting 2 instead of 3 cookie headers response. how allow re-directs ? input nice. my code is: defaulthttpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(url); try { httppost.setparams(new basichttpparams().setparameter("a", "b")); httppost.setparams(new basichttpparams().setparameter("c", "d")); httppost.setparams(new basichttpparams().setparameter("e", "f")); httppost.setparams(new basichttpparams().setparameter("g", "h")); httppost.setparams(new basichttpparams().setparameter("i", "j")); httppost.setparams(new basichttpparams().setparameter("k", "l")); httppost.setparams(new basichttpparams().setparameter("m", bundle.getstring("responsedata"))); urlencodedformentity formentity = new urlencod

How do I apply an AngularJS directive based on a class set by ng-class? -

i'm trying conditionally apply directive element based on class. here's simple case of issue, see results in fiddle . example, i'm using map of class names booleans form of ng-class true ; in actual case i'd use boolean result of function. markup: <div ng-app="example"> <div class="testcase"> have directive applied expect </div> <div ng-class="{'testcase':true}"> not have directive applied expect </div> </div> js: angular.module('example', []) .directive('testcase', function() { return { restrict: 'c', link: function(scope, element, attrs) { element.css('color', 'red'); } } } ); why isn't directive being applied div that's getting class through ng-class ? misunderstanding order in angularjs processing directives? how should conditionally applying direc

visual studio - Filters vs. File Paths VS2008 -

where work, there significant difference between how solution explorer filters setup , filepaths source files located, makes finding source files in solution explorer difficult when know on drive. i've included link screenshot clarity. is there way change the view of solution explorer show actual folder structure instead of file filters? screenshots: http://imgur.com/a/txalx thanks! james yes, there is. select project node , @ top of solution explorer click "show files" button. (disclaimer: implemented feature in vs 2005 visual c++). note solution explorer show sub-directories of project directory. files outside of project directory structure show "links".

eclipse - Failed to connect to remote VM. Connection refused. when trying to debug remote java application in Flash Builder 4.7 -

Image
at 1 point, remote debug used work. life of me, don't seem able figure out broke it. i have flex/java application. there wrapper starts tomcat server. modified wrapper.conf file include -xdebug -xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n in flex debug configurations, on left, have remote java application. on right, have standard (socket attach) connection type, 127.0.0.1 (i have tried localhost too) host, , 8000 port. the following stack trace. !entry org.eclipse.jdt.launching 4 113 2013-09-03 11:30:49.109 !message failed connect remote vm. connection refused. !stack 0 java.net.connectexception: connection refused: connect @ java.net.plainsocketimpl.socketconnect(native method) @ java.net.plainsocketimpl.doconnect(unknown source) @ java.net.plainsocketimpl.connecttoaddress(unknown source) @ java.net.plainsocketimpl.connect(unknown source) @ java.net.sockssocketimpl.connect(unknown source) @ java.net.socket.

javascript - Navigation property not properly loaded -

in application, have 2 ef entities, user , company. these 2 entites have 1 1 relationship. public class company : ientity { public virtual int id { get; set; } [required] public virtual user owner { get; set; } public virtual string name { get; set; } public virtual string address { get; set; } public virtual byte[] logo { get; set; } } and user: public class user : ientity { [notmapped] public virtual int id { get; private set; } [key] [required] public virtual string email { get; set; } public string name { get; set; } public virtual company company { get; set; } } i query these objects following breeze js code: var query = entityquery.from('currentuser').expand('company'); the web api controller has these 2 methods: [httpget] public iqueryable<user> currentuser() { var username = ... return _breezecontext.context.users.find(sup => sup.email.equals(username)).asqueryable(); } [http

node.js - Cant run node js as root -

i have node js running on raspberry pi. when run $ node -v gives me version number when run $ sudo node -v returns node: not found i need run root, ideas? when run root, path different. if modify path root, or specify full path node.js executable, work.

ios - Core Data NSFetchrequest integer -

i have following scenario. have app handles data using core data. have entity called "brothers" has 3 attributes: name, status, age. lets have 1 record on database has: -name ==> joe (string) -status ==> married (string) -age ==> 28 (integer) i have uilabel uitextfield , button. want able type name (in case joe) on uitextfield press button , display age (in case 28) in uilabel. store age value variable type integer can make calculations later on. below code have inside button. nsentitydescription *entitydesc = [nsentitydescription entityforname:@"brothers" inmanagedobjectcontext:context]; nsfetchrequest *request = [[nsfetchrequest alloc]init]; [request setentity:entitydesc]; nspredicate *predicate = [nspredicate predicatewithformat:@"age %d", [self.age.text integervalue]]; [request setpredicate:predicate]; nserror *error; nsarray *integer = [context executefetchrequest:request error:&error]; self.displaylabel.text = integ

java - creating two dimensional hashset functionality -

i trying make 2 dimensional hashset functionality. have loop iterates through pairs of integers: resultset getassociations; statement getassociationsselect = sqlconn .createstatement(); getassociations = getassociationsselect .executequery("select productid, themeid producttheme"); while(getassociations.next()) { int productid1 = getassociations.getint(1); int themeid1 = getassociations.getint(2); } when current pair of integers not match previous pair of integers want store them. figured hashset best approach because can insert pairs , wont take repeats. how do this? if want simple solution concatenate both keys , store resulting string, e.g. string newkey = string.format( "%d-%d.", productid1 , themeid1 ); it allways generate unique key each combination.

yii - behat step "I should see" does not see -

using behat in yii framework, observing quite strange behaviour: behat not find text when using steps then should see "some text" some text finds normaly, - not. sure on page think on, i've added sort of markers in view files , behat sees them. so, scenario scenario: editing journal given following journals present: | name | link | description | | murzilka | http://www.murz.com | advanced child journal| | nature | www nature com | nice journal | when on edit page journal "nature" should see "update nature" should see "nice journal" should see "1qazxsw2" <-- marker should see "2wsxcde3" <-- marker should see "www nature com" the output then scenario: editing journal # features\journal.feature:21 given following journals present: # featurecontext::thefollo

java - 80+ R cannot be resolved to a variable errors and No resource found that matches the given name -

all of sudden i'm getting 80+ r cannot resolved variable errors after modifying strings.xml file. i'm not sure i've done cause issue i've wrecked project somehow , when check network drive workspace resides - strings files there , can open in eclipse , see supposed "missing strings" eclipse states: no resource found matches given name regardless of fact strings infact there. steps taken: clean project examine strings.xml abnormalities (none found) restart eclipse strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">welcome <b>straight talk wireless!</b></string> <string name="app_name">straight talk data settings</string> <string name="display_name">data settings</string> <string name="initial_sm_dialog">the apn settings on phone updated straight talk wireless network ca

javascript - jQuery do something when select options' values are not empty/NULL -

here's scenario. supposing have multiple <select> 's on page (can 0,1,2,3,4 or more) , want piece of code fire when option values not equal "" or null . there quick fire method in jquery find this? selects in <div> tag class of class="variations" no useful classes or id's selects present dynamically generated based on current page/product id. i can work when 1 or other not equal "" or null can't seem fire when both selected (and fire again when both unselected, if makes sense). you may try this $('.variations').on('change', 'select', function(){ if(this.value){ // } }); demo.

Adding special characters to Python regex engine -

i have project searching bytecode instructions , expand allow use of regular expressions matching patterns. the gist of want have custom character classes/sets can have such istore match of following instructions: istore istore_0 istore_1 istore_2 istore_3 and similar iload ... iload_n etc. istore , iload similar metacharacters \s stand multiple characters. basically looking jumping off point can find way implement own metacharacters. you don't need modify regex engine (which quite difficult) you need helper function convert flavour of regex python's in same way use re.escape def my_re_escape(regex): regex = re.escape(regex) regex = regex.replace('foo', 'bar') # etc return regex

apache - htaccess Redirect sub directories except index.php -

i have htaccess file in www.mydomain.com/dir. i want redirect requests www.mydomain.com/dir/* www.mydomain.com/dir except www.mydomain.com/dir/index.php i tried this: rewriteengine on rewritecond document_root/ !-f rewriterule ^/*$ index.php what doing wrong? that works almost! www.mydomain.com/dir/.htaccess: options +followsymlinks -multiviews rewriteengine on rewritebase /dir/ rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule (?!^index\.php$)^.+$ index.php [l,nc] but when access file or sub directory in dir 404. index.php located in dir , request file or sub directory in dir should redirected dir/index.php .

html - How to position a div on bottom of box flex container -

i trying position div on bottom of each child next each other in 1 row , expanded parents height. my html looks this: <div class="parent"> <div class="child"> <div class="bottom">footer</div> </div> <div class="child"> <div class="bottom">footer</div> </div> <div class="child"> <div class="bottom">footer</div> </div> </div> this have come with: http://jsfiddle.net/xtvdq/ but can not position div.bottom on bottom of div.child. is there way accomplish this? if remove box related css works expected, lose height expansion parent container. so not easy: javascript not option here. change css following .parent { position:relative; display:-moz-box; display:-webkit-box; display:box; -moz-box-orient: horizontal; -webkit-box-orient: horizontal; box-orient: horizonta

java - Mysql DB connection with JDBC freezing program -

i have mysql jdbc library added eclipse project still cant connect database, program doesn't throw error, freezes on me. here's link library used http://dev.mysql.com/downloads/connector/j , current code ( username, host, , passwords omitted. private connection connect = null; private statement statement = null; private preparedstatement preparedstatement = null; private resultset resultset = null; @override try { // load mysql driver, each db has own driver class.forname("com.mysql.jdbc.driver"); // setup connection db connect = drivermanager .getconnection("jdbc:mysql://host:8080/feedback?" + "user=******admin&password=********"); // statements allow issue sql queries database statement = connect.createstatement(); // result set result of sql query system.out.println("connected"); } catch (exce

java - How to know mouseDragged direction - when it's up or down? -

finishing create custom scrollbar, , question is: addmousemotionlistener(new mousemotionadapter() { @override public void mousedragged(mouseevent e) { //how know mouse direction - or down? } }); maybe there simple method, or have manually? you have manually need mouseadapter instead of mousemotionadapter record initial y co-ordinate. addmousemotionlistener(new mouseadapter() { int previousy; @override public void mousepressed(mouseevent e) { previousy = e.gety(); } @override public void mousedragged(mouseevent e) { int y = e.gety(); if (y < previousy) { system.out.println("up"); } else if (y > previousy) { system.out.println("down"); } previousy = y; } });

python - .get and dictionaries -

i'm new python programmer , reading on .get method dictionaries, tried use myself. tried simple code: h = dict() h.get('a', 1) print (h) and interpreter returned only: {} i know .get method returns default value provide if can't find key asked for, go , create new key , bucket in dictionary? if so, why doesn't code return new item? thanks no, get not add entry dict if 1 doesn't exist. makes no modifications. >>> h = dict() >>> h.get('a', 1) 1 >>> h {} the same goes [] when reading dict; throw error non-existent keys. different c++, [] add entries if aren't there already. >>> h['a'] traceback (most recent call last): file "<stdin>", line 1, in <module> keyerror: 'a' >>> h {} but know python can differentiate between reads , writes. assigning non-existent key create it, though reading non-existent key raises exception. >>> h[&

matrix - Finding generalized eigenvectors numerically in Matlab -

i have matrix such example (my actual matrices can larger) a = [-1 -2 -0.5; 0 0.5 0; 0 0 -1]; that has 2 linearly-independent eigenvalues (the eigenvalue -1 repeated). obtain complete basis generalized eigenvectors . 1 way know how matlab's jordan function in symbolic math toolbox, i'd prefer designed numeric inputs (indeed, 2 outputs, jordan fails large matrices: "error in mupad command: similarity matrix large."). don't need jordan canonical form, notoriously unstable in numeric contexts, matrix of generalized eigenvectors. there function or combination of functions automates in numerically stable way or must 1 use the generic manual method (how stable such procedure)? note : "generalized eigenvector," mean non-zero vector can used augment incomplete basis of so-called defective matrix . not mean eigenvectors correspond eigenvalues obtained solving generalized eigenvalue problem using eig or qz (though latter usage qu

How many urls can be queried using Facebook's FQL api? -

looking query like: select url,like_count, total_count, share_count, click_count link_stat url in("http://bing.com", "http://google.com", "http://facebook.com", "http://twitter.com") i haven't been able find documentation limits number of urls can queried @ 1 time.

javascript - Create numbered list in KnockoutJS using each item's position in an observable array for the numbers -

i create numbered list , use knockout bind data. data binding works fine, unable come way smoothly generate numbers based on position in observable array. observable array may vary in future, knockout dynamically handle numbering of list. here html: <ul class="nav nav-list" data-bind="foreach: sidebaritems"> <li class="" data-bind="css: isactive"> <a href="#dropdowns" data-bind="text: text"></a> </li> </ul> here javascript code: self.sidebaritems = ko.observable([ {text: 'option'}, {text: 'option'}, {text: 'option'}, {text: 'option'}, {text: 'option'} ]); i list say: 1 - option 2 - option 3 - option etc. see documentation: http://knockoutjs.com/documentation/foreach-binding.html use $index : <ul class="nav nav-list" data-bind="foreach: sidebaritems"> &l

How to retrieve headers on AppHarbor hosted WCF-applications -

currently have wcf-based service deployed on appharbor. i'm having issue operation defined this: [webget(uritemplate = "feedcallback")] stream handlemessageget(); and implemented this: public stream handlemessageget() { var value = weboperationcontext.current.incomingrequest.headers["header.name"]; //do stuff header value return ms; } whenever run wcf application on localhost debugging etc. works fine; can retrieve header value. whenever deploy project appharbor, request doesn't function anymore because can't retrieve header weboperationcontext . what causing issue , how solved? in end seems issue appharbor loadbalancer not forwarding headers dots in them. see: http://support.appharbor.com/discussions/problems/37218-header-not-being-forwarded

python - Flask: URLs w/ Variable parameters -

i have url string want build in following manner: http://something.com/mainsite/key1/key2/key3/keyn how generate in url mapping n variable number? how keys? thanks there 2 ways this: simply use path route converter : @app.route("/mainsite/<path:varargs>") def api(varargs=none): # mainsite/key1/key2/key3/keyn # `varargs` string contain above varargs = varargs.split("/") # , list of strings register own custom route converter (see werkzeug's documentation full details): from werkzeug.routing import baseconverter, validationerror class pathvarargsconverter(baseconverter): """convert remaining path segments list""" def __init__(self, url_map): super(pathvarargsconverter, self).__init__(url_map) self.regex = "(?:.*)" def to_python(self, value): return value.split(u"/") def to_url(self, value): return u"/"

c# - TrimStart in Expression Tree with LINQ to Entities -

i'm attempting write expression tree can allow dynamic use of startswith() method on non-string valued columns using entity framework. e.g. integervaluedcolumn.startswith(5) return 500 , 5000 , 555 , 5123 , etc i trying write expression tree based on answer: how query integer column "starts with" in entity framework? here have far: methodinfo stringconvert = typeof(sqlfunctions).getmethod("stringconvert", new[] { typeof(double?) }); expression castexpression = expression.convert(propertyexpression, typeof(double?)); expression convertexpression = expression.call(null, stringconvert, castexpression); methodinfo trimstart = typeof(string).getmethod("trimstart"); expression nullexpression = expression.constant(null, typeof(char[])); expression trimexpression = expression.call(convertexpression, trimstart, nullexpression); methodinfo startswith = typeof(string).getmethod("startswith", new[] { typeof(string) }); expression me

Rails and SQL - Joining by multiple table columns -

i'm still trying learn sql , use ordering different attributes. i'm trying products , skus , order them first collection.name , sku.name . however, both collection name , sku name in different tables associated products table foreign key. so this product.id | collection.name | product.name | sku.name 1 | apple | lateral file | a34 3 | beaumont | desk | bt450 2 | beaumont | hutch | bt451 5 | beaumont | drawer | bt452 7 | vista | file | v246 6 | waterfall | tv stand | wf899 any appreciated here models: product.rb class product < activerecord::base attr_accessible :name, :title, :features, :collection_id, :skus_attributes belongs_to :collection has_many

php - How to generate table rows based on data in database -

Image
i trying take style of code , generate based on how many machines returned database. i have this: <table style="width: 100%; height:85%;table-layout:fixed;text-align:center;"> <tr> <td><?php echo $array[0]; ?> <span class="blue">#1</span><br> sets <span class="blue">1</span> reps <span class="blue">50</span><br> weight <span class="blue">25</span></td> <td><?php echo $array[1]; ?> <span class="blue">#2</span><br> sets <span class="blue">1</span> reps <span class="blue">100</span><br> weight <span class="blue">40</span></td> </tr> <tr> <td><?php echo $array[2]; ?> <span class="blue">#3</span><br> sets <span class="blue">