Posts

Showing posts from June, 2014

Python version of ssh -D (SOCKS proxy over SSH) -

i'm trying use urllib2 on proxy scrap web page isn't directly available (it's running in remote server's local network , isn't externally accessible). proxy i'd prefer ssh socks proxy (like if run ssh -d 9090 server ), both because have access , because it's secure. i've had poke around paramiko find points running ssh connection out on socks, opposite of i'm trying accomplish here. i have seen transport class dumb forwarding , doesn't provide nice openssh-socks proxy interface can latch onto socksipy (et al). net::ssh::socks ruby i'm looking in wrong language. there available in python provides proxy on ssh? i have workaround works scraping. instead of trying use ssh connection, i'm using remote shell pull out data: from bs4 import beautifulsoup import paramiko ssh = paramiko.sshclient() ssh.load_system_host_keys() ssh.connect('example.com', username='oli', look_for_keys=true, timeout=5) stdin, st...

java - BufferedImage bytes have a different byte order, when running from Eclipse and the command line -

Image
i trying convert bufferedimage 's byte[] 32-bit rgba 24-bit rgb. according this answer fastest way byte[] image is: byte[] pixels = ((databufferbyte) bufferedimage.getraster().getdatabuffer()).getdata(); so iterate on bytes assuming order r g b , every 4 bytes, write first 3 in output byte[] (i.e. ignoring alpha value). this works fine when run eclipse , bytes converted correctly. when run same program command line same bytes returned opposite byte order! the test image use test 5x5 black image top-left corner different having rgba color [aa cc ee ff] : and zoomed-in version conveniency: my folder structure is: - src/ - test.png - test/ - testbufferedimage.java the sscce following: package test; import java.awt.image.bufferedimage; import java.awt.image.databufferbyte; import java.io.ioexception; import java.io.inputstream; import javax.imageio.imageio; public class testbufferedimage { private static void log(string s) { system.ou...

c# - 403 Forbidden error with HttpWebRequest -

i'm making web request redirects user url , fetches data. in browser, redirects & returns result redirected url. however, doesn't work console application: httpwebrequest webrequest = (httpwebrequest)webrequest.create(url1); webrequest.keepalive = true; webrequest.method = "get"; webrequest.contenttype = "text/plain"; webrequest.timeout = 20000; webresponse webresponse = webrequest.getresponse(); encoding enc = system.text.encoding.getencoding("utf-8"); streamreader loresponsestream = new streamreader(webresponse.getresponsestream(), enc); string result = loresponsestream.readtoend(); here result is: <html><body>you being <a href=\"..........................\">redirected</a>.</body></html> so need data href url of anchor tag. var matches = regex.matches(result, @"<a\shref=""(?<url>.*?)"">(?<text>.*?)</a>"); console.writeline(matc...

asp.net - How to make real time visit page -

i want make real time visit page take data database. use repeater binds dataset. works fine, when new row added, want show effect in feedjit's "real time visits" page. i used jquery this: $(document).ready(function () { $('.fadein').click(function () { $('.show').show('slow'); }); }); $(document).ready(function () { $(".fadein").trigger('click') }); but doesn't work. slides down whole repeater. should use other repeater or jquery problem? use long pulling comet or signalr signalr best options real time updates.

height - Vertical spacing of cells containing a parbox -

i have complicated longtable several levels of nested tabular environments. text wrapping inside cells , have contents aligned @ top use \parbox[t][][t], however, height of parbox computed without margin such following \hline overlaps text. a minimal example reproduce behavior is \documentclass{article} \begin{document} \begin{tabular} {|p{0.2\textwidth}|} \hline cell looks good. \\ \hline \parbox[t][][t]{1.0\linewidth}{ not happy this. } \\ \hline \end{tabular} \end{document} this produces following output (sorry, can't post images yet): image of generated output of course, there no reason use parbox in example above, need them in actual document. i avoid providing height of parbox (such \parbox[t][5cm][t]). there clean way add margin either bottom of parbox or before hline? sorry answer own question, have found solution adding vspace each cell outside parbox. here's code: \documentclass{article} \begin{document} \newcommand{\p...

mysql - C3p0 APPARENT DEADLOCK exception -

i keep getting exception in tomcat log: com.mchange.v2.async.threadpoolasynchronousrunner$deadlockdetector run warning: com.mchange.v2.async.threadpoolasynchronousrunner$deadlockdetector@76b28200 -- apparent deadlock!!! creating emergency threads unassigned pending tasks! com.mchange.v2.async.threadpoolasynchronousrunner$deadlockdetector run warning: com.mchange.v2.async.threadpoolasynchronousrunner$deadlockdetector@76b28200 -- apparent deadlock!!! complete status: managed threads: 3 active threads: 3 active tasks: com.mchange.v2.resourcepool.basicresourcepool$acquiretask@1201fd18 (com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#1) com.mchange.v2.resourcepool.basicresourcepool$acquiretask@408f3be4 (com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#0) com.mchange.v2.resourcepool.basicresourcepool$acquiretask@7ba516d8 (com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#2) pending tasks: com.mcha...

Python Spynner Filling HTML Fields -

i'm trying fill fields on http://www.united.com/web/en-us/apps/booking/flight/searchaward.aspx?sb=1&cs=n . however, can't work. as example, "from" field in "where , when want fly?" box. import spynner b = spynner.browser() b.show() b.load('http://www.united.com/web/en-us/apps/booking/flight/searchaward.aspx?sb=1&cs=n') b.wk_fill('input[name=ctl00$contentinfo$searchform$airports1$origin$txtorigin]', 'london, england (lhr - heathrow)') b.browse() # see what's going on. when try this, field isn't filled. appreciated! you need use quotes b.wk_fill('input[name="ctl00$contentinfo$searchform$airports1$origin$txtorigin"]', 'london, england (lhr - heathrow)') with quotes works fine. p.s. sorry bad english.

bash - Nagios plugin script not working as expected -

below script, in using jvmtop.sh script's output store in respected variables , later processing in nagios graphs. in client server bash, script outputs expected. when test check command in nagios, seems ./jvmtop.sh doesn't store output in variable. getting "critical - process monitor not running!" let me know missing.. get_vals() { current=/usr/local/nagios/libexec/ cd $current oldifs=$ifs ifs='\n' tmp_output=$(./jvmtop.sh --once | grep $process) ifs=$oldifs if [ -z "$tmp_output" ] echo "critical - process monitor not running!" exit $st_cr fi pid=`echo ${tmp_output} | awk '{print $1}'` hpcur=`echo ${tmp_output} | awk '{print $3}' | sed 's/.$//'` hpmax=`echo ${tmp_output} | awk '{print $4}' | sed 's/.$//'` nhcur=`echo ${tmp_output} | awk '{print $5}' | sed 's/.$//'` nhmax=`echo ${tmp_output} | awk '{print $6...

c++ - logical drive letters are not displaying -

i have written small program search logical drives in pc , prints them. differnt wirh expected, not displaying them.. here code sample tchar szdrive[] = (" a:"); dword drive = getlogicaldrives(); printf("the bitmask of logical drives in hex: %0x\n", drive); printf("the bitmask of logical drives in decimal: %d\n", drive); if(drive == 0) printf("getlogicaldrives() failed failure code: %d\n", getlasterror()); else { printf("this machine has following logical drives:\n"); while(drive) { // use bitwise and, 1â€"available, 0-not available if(drive & 1) printf("%s ", (const char *)szdrive); // increment, check next drive ++szdrive[1]; // shift bitmask binary right drive >>= 1; } printf("\n "); } your printf statement broken. use this: printf("%s ", szdrive); i guess use of %s instead of %s typo.

php - how to create a '.png' image from a flash object -

how create '.png' image flash object. currently using 'openflashchart' in application, works , shows me flash of bar or pie chart, want store '.png' image of chart in folder. note : have removed 'ofc_upload_image.php' file library has vulneribilities. so, want convert flash '.png' image. thanks in advance taking screenshot in swf , encoding straightforward: var screen:bitmapdata = new bitmapdata(stage.stagewidth, stage.stageheight); screen.draw(stage, null, null, null, new rectangle(0, 0, stage.stagewidth, stage.stageheight)); var encoder:pngencoder = new pngencoder(); var png:bytearray = encoder.encode(screen); you can replace rectangle params necessary capture portion (e.g. chart). i'm going assume wanting upload image server, in case can use urlloader send byte array containing encoded png data: var request:urlrequest = new urlrequest(your_url); request.contenttype = "application/octet-stream"; requ...

How do I run my Flask app remotely using MongoHQ and Heroku (Python) -

i have script written in python lets me consume tweets terminal locally hosted mongodb database. improve uptime, host script remotely on heroku , shoot consumed tweets database hosted mongohq. without using django, use flask framework deploy app heroku (described here: https://devcenter.heroku.com/articles/python ). when run simple "hello world" app using setup, fine. however, when try run tweet consuming app, crashes. how can change app work flask/heroku/mongohq setup? source code is: import json import pymongo import tweepy consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" auth = tweepy.oauthhandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.api(auth) class customstreamlistener(tweepy.streamlistener): def __init__(self, api): self.api = api super(tweepy.streamlistener, self).__init__() self.db = pymongo.mongoclient().test...

Rails - joining a github project with a missing database -

i trying collaborate on project has following .gitignore: # ignore bundler config. /.bundle # ignore default sqlite database. /db/*.sqlite3 /db/*.sqlite3-journal # ignore logfiles , tempfiles. /log/*.log /tmp # ignore other unneeded files. database.yml doc/ *.swp *~ .project .ds_store .idea .secret so database missing, along related files, makes rails throw me error if try start server, , rake aborted! errors if try run db:create/migrate/ etc (yml file not found, adapter not specified). any pointers @ how can tackle problem in correct/effective way? you're never supposed supply database project. normal thing create it: the database.yml file should define name of database, rake db:create should create you. the schema should either defined in schema.rb file in case run rake db:schema:load or can provided via migrations (or both). in second case run rake db:migrate . if migrations defined (and should be), 2 options equivalent. if application needs data ru...

How to detect mouse clicking in vb.net? -

i want program when user click on either in application or outside of that, make screen shot , save jpeg folder this code want put option in it: imports system.net.mail public class form1 private function takeimage() return takeimage(0, 0, screen.primaryscreen.workingarea.width, screen.primaryscreen.workingarea.height) end function private sub form1_load(byval sender system.object, byval e system.eventargs) handles mybase.load picturebox1.image = ctype(takeimage(), image) end sub end class by way i'm beginner in vb.net i guess desktop application , takeimage(,,,) works. in form, add button, double click , call takeimage there. there saving jpeg - google on how convert bitmap(?) format takeimage jpeg , google how save it. in vb.net should rather easy handle files. but first set return type on takeimage function. as image . doesn't change program practice , aid in learning editor continuously give helping feedback. happy hacking!

postgresql - Postgres escape a single quote -

i have following postgres query: select sum(cost) db id not in (<parameter>) <parameter> dynamic text field multiple id's need inserted. if type in 123, 456 as id's, results in: select sum(cost) db id not in ('123,456') which doesn't run properly. i can change query, can't change input field. if type in 123','456 it results in: select sum(cost) db id not in ('123'',''456') when change query into: select sum(cost) db id not in ('<parameter>') and type in 123,456 results in: select sum(cost) db id not in (''123'',''456'') i've got working mysql, not postgresql. idea how trick postgresql? try like: select sum(cost) db id != all(('{'||'123,456'||'}')::numeric[]) it form array string input values : {123,456} , cast array , check id against elements of array.

Android: AdapterView lags when dynamically adding view to LinearLayout -

i'm creating music player application. music library activity viewpager 4 pages/fragments (corresponding albums, artists, songs , playlists). 3 of fragments gridview 's , last 1 listview (the songs fragment). when application first started runs smoothly. however, when user selects song play (for first time) linearlayout (called 'now playing bar') dynamically created @ bottom of screen information playing song. @ points of gridview 's , listview begin lagging quite badly when scrolled. weirdly enough viewpager doesn't seem experience lag switching between fragment 's seamless before. problem persists when user exits player , resumes (in case 'now playing bar' visible). there rather confusing factor in this. when user selects album, artist or playlist library creates new activity listview containing songs said artist/album/playlist. 'now playing bar' added activity causes no slowdown whatsoever. leads me conclude problem related vie...

Drawing Gantt charts with R to sub-second accuracy -

slightly bizarre request, know, bear me. i have excel spreadsheet logging data taken highly parallelised bit of server-side code. i'm trying analyse there may gaps in logs, indicating tasks should logged aren't; because it's serial, timestamp-order list of dozen or parallel threads it's quite hard read. had unorthodox idea of using gantt chart visualise overlapping tasks. excel terrible @ this, started looking @ alternative tools, , thought of trying r. each task in log has start timestamp, , end timestamp, , duration, have data need. read this post , mutilated example r script: tasks <- c("task1", "task2") dfr <- data.frame( name = factor(tasks, levels = tasks), start.date = c("07/08/2013 09:03:25.815", "07/08/2013 09:03:25.956"), end.date = c("07/08/2013 09:03:28.300", "07/08/2013 09:03:30.409"), is.critical = c(true, true) ) mdfr <- melt(dfr, measure.vars = c("sta...

Why am i getting an unexpected operator error in bash string equality test? -

this question has answer here: /bin/sh: odd string comparison error 'unexpected operator' [duplicate] 3 answers where error on line four? if [ $bn == readme ]; which still if write if [ $bn == readme ] or if [ "$bn" == "readme" ]; context: for fi in /etc/uwsgi/apps-available/* bn=`basename $fi .ini` if [ $bn == "readme" ] echo "~ ***#*** ~" else echo "## shortend convience ##" fi done you can't use == single bracket comparisons ([ ]). use single = instead. must quote variables prevent expansion. if [ "$bn" = readme ]; if use [[ ]], apply , wouldn't need quote first argument: if [[ $bn == readme ]];

javascript - How do i make so the div's overlap with eachother? -

how make when press button instead of div dropping under div the maybe 'home' div disappear when fire other show hidden div ? here's javascript: jquery(document).ready(function () { jquery('#hideshow2').live('click', function (event) { jquery('#content2').toggle('show'); }); }); pretty easy..... see fiddle. http://jsfiddle.net/rcfvx/ jquery(document).ready(function () { jquery('#homebtn').click(function (event) { jquery('#one').toggle(); jquery('#two').toggle(); }); });

c# - Design Patterns for User Registration process -

during interview asked create sample application user registration/login following requirements should have layered architecture use design patterns (at least 2) abstract programming basic validation i completed assignment without using design patterns. design pattern have been appropriate user registration? this question maybe duplicate of this question in answer have suggested using microsoft membership provider, not possible implement layered architecture? i hate when 1 forces me use design pattern because should emerge out of design. anyway, if had use sake of using go repository pattern structuring data access layer , use separated interface design pattern mentioned martin fowler implement that, , stuff in one, go layer supertype pattern , make base class domain layer entities such user, admin, login_info, etc.

c++ - Performant Way to create checkerboard pattern -

so have image want overlay checkerboard pattern. have come far: for ( uint_8 nrow = 0; nrow < image.width(); ++nrow) (uint_8 ncol = 0; ncol < image.height(); ++ncol) if(((nrow/20 + ncol/20) % 2) == 0) memset(&image.data[ncol + nrow], 0, 1); produces white image unfortunately. dont think performant because memset called every single pixel in image instead of multiple. why code not produce chckerboard pattern? how improve it? for better performance, don't treat image 2-dimensional entity. instead, @ 1d array of continuous data, lines of image arranged 1 after other. with approach, can write pattern in 1 go single loop, in every iteration memset() multiple adjacent pixels , increase index twice amount of pixels set: int data_size = image.width() * image.height(); (auto = image.data; < image.data + data_size; += 20) { memset(it, 0, 20); if (((it - data) + 40) % (20 * 400) == 0) { += 40;...

visual studio 2010 - The Following Module was built either with optimizations enabled or without debug information after frame work is changed to 4.0 from 3.5 -

Image
i using vs2010.i changed project , dependent projects .net framework 4.0 3.5.now not attach process,due not able debug code. have cleaned bin folders , rebuild projects ,but still having following error. please me resolve this.. i'm not sure question here. error message tells you need turn off (disable) optimizations turn on (enable) debug info rebuild project changes take effect. apparently did step #3. also see vs2010 debugging module built without debugging information? , may provide more information.

c# - WPF client to screen point transformation -

i'm looking way transofrm given points relative visual points on screen. found solution: http://social.msdn.microsoft.com/forums/vstudio/en-us/b327c0bc-d27e-44fe-b833-c7db3400d632/how-to-get-control-location-in-screen-coordinate-system i can't understand different beween pointroot , pointclient seem equal time: // [...] // translate point visual root. generaltransform transformtoroot = relativeto.transformtoancestor(root); point pointroot = transformtoroot.transform(point); // transform point root client coordinates. matrix m = matrix.identity; transform transform = visualtreehelper.gettransform(root); if (transform != null) m = matrix.multiply(m, transform.value); vector offset = visualtreehelper.getoffset(root); m.translate(offset.x, offset.y); point pointclient = m.transform(pointroot); // [...] (for full code click on link) it seems visualtreehelper.getoffset(root) tries transform of window... assuming visual comes button control... looking...

sql - How to reference another Database in a generic manner -

we have live , demo systems, each using of pair of databases. 1 database reports other. quite demo site has reference this select columns otherdatabase_demo.dbo.tablename so live version say: ...from otherdatabase.dbo.tablename when comes publsihing compare stored procedures between live , demo (using dbforge schema compare in case) every differing reference highlighted, , creates lot of noise. is there way abstract these references can make distinction in 1 single location? yes, use synonym. in 1 database: create synonym dbo.mytablename otherdatabase_demo.dbo.tablename; and in live version: create synonym dbo.mytablename otherdatabase.dbo.tablename; now script can say... select columns dbo.mytablename ...in both databases, allowing procedures identical. your diff scripts may pick different definitions synonyms, can ignore (either tool or consciously). we've asked ability alias database, don't understand how useful be: http:...

c++ - [Qt]How to support :pressed state of style sheet for custom widget? -

what have :- i have custom widget extends qframe (instead of qwidget qframe has working paintevent implementation). have overridden mousepressed() , mousereleased() emit pressed() released() , clicked() signals. upto point woring fine expected. what need :- this custom widget having basic style sheet support , supports :hover state fine. :pressed state not working. have figured out bcoz not supported qframe/qlabel etc. wish know need in order support :pressed state. should set attribute / property on pressed , released or else ? you can set property qlabel (or whatever widget using) , change value of property. use property in stylesheets. example: this->setstylesheet("*[myproperty=\"true\"] { background-color: red }"); d_label = new qlabel("dynamic label", this); d_label->setproperty("myproperty", false); then in mousepressevent set , in mousereleaseevent unset property: d_label->setproperty("myproperty...

javascript - Openlayers - coordinates saving after drag cause point go to 0,0 -

i have map dragable point , after drag, update latitude , longitude fields in form. when this: drag = new openlayers.control.dragfeature(vectors, { autoactivate: true, oncomplete: function() { $('#place_latitude').val(point.transform(mapp, wgs84).y); return $('#place_longitude').val(point.transform(mapp, wgs84).x); } }); after attempt make second drag (from 1 point another) point goes 0,0. without oncomplete ok. you transforming point 2 times... transform method modifies point itself, doesn't create new object. you may use point.clone() instead of point .

jquery - JVectormap - Different Border/Stroke width for State and Regions -

i using jvectormap displaying regions , states geojson data. takes regions stroke width show state borders. want different border/stroke width regions , states. code snippet setting border style - regionstyle: { initial: { fill: "white", "fill-opacity": 1, stroke: "red", "stroke-width": 0.2, "stroke-opacity": 1, } }, some appreciated.

Tempo and time signatures from MIDI -

i'm building software displaying music notes midi file. can every letter of tones noteon , noteoff events don`t know how or how calculate types of notes (whole, half, eigth..) , other time signatures. how can it? looked example without success. midi doesn't represent notes in absolute quantities, in classical music. instead, length of note continues until corresponding note off event parsed (also it's quite common midi files use note on event 0 velocity note off, keep in mind). need translate time in ticks between 2 events musical time know whether use whole, half, quarter note, etc. this translation depends on knowing tempo , time signature, midi meta events. more information parsing can found here: http://www.sonicspot.com/guide/midifiles.html basically take ppq find number of milliseconds per tick, use time signature , tempo find length of quarter note in milliseconds. there answers on stackoverflow conversion, i'm writing post on phone , can't...

c# - Thread safe file access -

i have program large number of comparisons. compares specific .dat file saved on local machine large number of other files generated on run-time. right unable perform these comparisons using multiple threads because of many system.accessviolationexception . i'm assuming because multiple threads trying access same local file @ same time. how can overcome these comparisons multiple threads? there several possible reasons access violation: multiple threads exclusively locking specific .dat file your multi-threading buggy in regard multiple threads try read same runtime generated file your multi-threading buggy in regard threads try read runtime generated files before have been generated completely the following solutions exist: read .dat file memory once , share data between threads. reduces i/o load make sure every runtime generated file compared 1 thread. can achieved thread safe queue contains files need compared , shared between threads. make sure runtime...

javascript - Error in the format of JSON -

i have json format : [15:17:37,612] ({rb:"0.6", i:[{id:"cost_reportings_timestamp", label:"cost_reportings_timestamp", type:"date", pattern:""}, {id:"bureau de m. le maire min-sum-cost_reportings_cost", label:"bureau de m. le maire", type:"number", pattern:""}, {id:"salle de r\xe9union min-sum-cost_reportings_cost", label:"salle de r\xe9union", type:"number", pattern:""}, {id:"secr\xe9tariat / accueil min-sum-cost_reportings_cost", label:"secr\xe9tariat / accueil", type:"number", pattern:""}], k:[{c:[{v:(new date(1354921200000))}, {v:0}, {v:1.8221145868301392}, {v:1.0604355335235596}]}, {c:[{v:(new date(1355007600000))}, {v:0}, {v:2.288118362426758}, {v:0}]}, {c:[{v:(new date(1355094000000))}, {v:0.4536628723144531}, {v:2.1034255027770996}, {v:1.1031612157821655}]}, {c:[{v:(new date(1355180400000))}, {v:0.4586494...

Javascript function not getting all values first time -

i trying let user upload list of items filter search results table by. problem not rows don't have values in filter list removed first time, program want need run multiple times. the attached code works, want remove 'badworkaround()' function <div align="center"> <script> function readlist() { var origtext = document.getelementbyid("cusiptextarea").value; var filterlist = origtext.split("\n"); var table = document.getelementbyid("resultstable"); var rows = table.getelementsbytagname("tr"); for(i = 1; < rows.length; i++) #first row has column names start @ i=1 { var found = '0' for(j = 0; j < filterlist.length; j++) { if (rows[i].innerhtml.indexof(filterlist[j]) > 0){ found = '1' break; } } if (found != '1'){rows[i].remove();} } } function badworkaround(){ readlist(); ...

javascript - Looking for responsive js carousel -

i trying find carousel in: http://whiteshoe.ferragamo.com simpler. need responsive full page carousel items have description , link on "active" mode, , others title , inactive, darker or greyish. ive tried 1 http://caroufredsel.dev7studios.com don't know how add inactive/active states, , responsive: true doesn't re size images. :) it's funny, seems responsive of responsive caroussel doesn't work in browser (on demo page)... there lot of responsive jquery caroussel anyway, you'll find 1 on google...

ruby on rails - Jquery fancybox doesnt show - only after page reload -

this view: <div id='profile_galery'> <ul> <li class='big'><%=link_to image_tag(@profile.user.get_avatar(:large) ), @profile.user.get_avatar(:very_large), :class => 'fancybox'%></li> and js: $(document).on("ready page:change", function() { $(".fancybox").fancybox({ openeffect : 'elastic' }); }); when go page image fancybox class , click on - there no fancybox but... html change , page locked. seems fancybox opened did not show , blocked everything. when reload page - fancybox works. whats going on? try add parent option $('.fancybox').fancybox({ parent: "body"});

Passing 'next' to django login template via urls.py -

i'm trying pass 'next' field login.html template via urls.py file using code this works fine: urls((r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}), but don't want redirect after login go '/accounts/profile/' page, want go site root, '/'. url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html', 'next':'/'}), but get login() got unexpected keyword argument 'next' not sure how pass 'next' argument via urls function , can't seem find other solutions, advice? i able this, url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html', 'extra_context': {'next':'/'}}),

how can i compare the index in iPhone -

i have taken indexes of array shown in tableview , want play @ didselectrowatindexpath same in index. mpmediaitem *item = [arranand objectatindex:3]; nsurl *url = [item valueforproperty:mpmediaitempropertyasseturl]; avplayeritem *playeritem = [[avplayeritem alloc] initwithurl:url]; player2 = [[avplayer alloc] initwithplayeritem:playeritem]; [player2 play]; here have pass 3 ..but need index match select @ did select row help!! the tableview:didselectrowatindexpath: pass indexpath object, contains index of selected table cell: - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { mpmediaitem *item = [arranand objectatindex:indexpath.row]; nsurl *url = [item valueforproperty:mpmediaitempropertyasseturl]; avplayeritem *playeritem = [[avplayeritem alloc] initwithurl:url]; player2 = [[avplayer alloc] initwithplayeritem:playeritem]; [player2 play]; } the indexpath.row give direct index if not have sections in tab...

javascript - jQuery: using localized variable -

Image
i trying use jquery cookie in order show/hide div element. var cexpiry = lu_ban_object.cexpiry; jquery('.float_close').click(function () { jquery('.float_notice').fadetoggle('slow'); jquery.cookie('noticevisibility', 'hidden', { expires: [cexpiry], //problem here path: '/' }); the expires: number , represents cookie expiry day. number being stored in array , localized, have assigned localized numebr cexpiry variable, not accepting brackets, [] have tried () , {} not working, +[cexpiry]+ i following error; uncaught typeerror: object [object array] has no method 'toutcstring' how change data type number? according screenshot saved string. expires needs date object or number. question, looks cexpiry number already, no need cast object or array wrapping in brackets. cexpiry might stored string, if that's cas...

python - How to connect to access (.mdb) database with pyodbc using latin-1 filename -

i use code connect access (.mdb) database: # -*- coding: latin-1 -*- filemdb = 'c:\\python27\\optimisateurlievre\\final\\archives_previsionsesp_août_2013.mdb' param = "driver={microsoft access driver (*.mdb)};dbq={%s};pwd={pw}" % filemdb con = odbc.connect(param) i following error: pyodbc.error: ('hy000', '[hy000] [microsoft][pilote odbc microsoft access] filename incorrect. (-1044) (sqldriverconnect); [hy000] [microsoft][pilote odbc microsoft access] filename incorrect. (-1044)') the problem seems come database filename û caracter. understanding of string , unicode, filemdb string encoded in latin-1. since, computer runs latin-1 encoding don't understand why filename incorrect. i work windows xp , python 2.7. thank help! it appears pyodbc tries convert connection string 'ascii' , characters above 0x7f invalid: con = pyodbc.connect(param) unicodedecodeerror: 'ascii' codec can't decode byte...

html - Make Text Overlap to 1px horizontal line -

i trying put text on horizontal line. want if text length increases line should adjusted according text length. working fine on ie7,8, mozilla. want make work google chrome. it's working fine except google chrome. here code: /*css*/ .pagehd{ font-size:30px; color:#369; font-weight:bold; padding:20px 0} .pagehd p{display:block; margin-right:10px} .title-line{ height:1px; border:0 none; background:#e5e5e5; position: relative; right:0; top:0px} <!--html--> <div class="pagehd"><p class="left">zones showcases</p> <hr class="title-line" /></div> can me this. thanks.! here's understand on question: you want make text overlap hr element. if i'm not mistaken on understanding question, answer. just make content after hr overlap hr. your new html be: <div class="pagehd"><hr class="title-line" /></div> and new css be: .pagehd { font-size:30px; ...

c++ - conversion operator with template functions -

i have class conversion operator std::string . works great except functions receiving std::basic_string<t> (templated on t ). #include <string> struct a{ operator std::string(){return std::string();} }; void f(const std::basic_string<char> &){} template<typename t> void g(const std::basic_string<t> &) {} int main(){ a; f(a); // works! g(a); // error! return 0; // because otherwise i'll lot of comments :) } the error receive error: no matching function call 'g(a&)' note: candidate is: note: template<class t> void g(const std::basic_string<_chart>&) now, know can define g friend in struct a , it'll work, problem lot of stl functions exist , receive std::basic_string<t> (for example, operator<< printing function, or comparison operators, or many other functions. i able use a if std::string . there way this? i able use i...

javascript - Enabling vendor prefixes in CSS transitions make callback fires twice -

i'm implementing excellent solution (found here ) use callback function a la jquery when using css transitions. the problem if use vendor prefixes, chrome @ least binds 2 events: 1 webkittransitionend , second 1 transitionend and, of course, fires callback twice. here's piece of code: jquery("#main").one('webkittransitionend otransitionend otransitionend mstransitionend transitionend', function(e) { console.log("poum!"); }); am doing wrong? you're not doing wrong. chrome uses both prefixed , un-prefixed versions. there couple options: using outside variable. var fired = false; jquery("#main").one('webkittransitionend otransitionend otransitionend mstransitionend transitionend', function(e) { if ( ! fired ) { fired = true; console.log("poum!"); } }); using kind of detection single variable transitionend (the below uses modernizr, , taken documentation ): var tran...

dynamics crm 2011 - Microsoft CRM Plugin Infinite Loop -

another ms crm question me, i'm afraid. i've got following code being executed on update of contact record gives me error saying job cancelled because includes infinite loop. can tell me why happening, please? // <copyright file="postcontactupdate.cs" company=""> // copyright (c) 2013 rights reserved // </copyright> // <author></author> // <date>8/7/2013 2:04:26 pm</date> // <summary>implements postcontactupdate plugin.</summary> // <auto-generated> // code generated tool. // runtime version:4.0.30319.1 // </auto-generated> namespace plugins3test { using system; using system.servicemodel; using microsoft.xrm.sdk; using microsoft.xrm.sdk.query; /// <summary> /// postcontactupdate plugin. /// fires when following attributes updated: /// attributes /// </summary> public class postcontactupdate: plugin { /// <summary...

c# - Updating Datagrid datacontext eats memory -

i have wpf datagrid , need update every minute. have added dispatchtimer data , update data context of datagrid. problem seems data sticking around. first thinking lists had lists running out updated datacontext , don't see megs of memory being used. dispatchertimer dispatchertimer = new dispatchertimer(); dispatchertimer.tick += new eventhandler(dispatchertimer_tick); dispatchertimer.interval = new timespan(0, 0, 1); i have set 1 second testing. private void dispatchertimer_tick(object sender, eventargs e) { observablecollection<technician> techdata = loaddata(); dg1.datacontext = null; dg1.datacontext = techdata; } ... private observablecollection<technician> loaddata() { observablecollection<technician> techdata = new observablecollection<technician>(); uri urigreenimage = new uri("pack://application:,,,/images/green.png"); uri uriredimage ...

javascript - Hide Input Field and Still Take User Input -

i working on project need hidden input field take user input. i have javascript in place focus on input field. when div visible can see typing. when hide div type , make div visible again not see change. how can make when div hidden, still take user input? really, if there way besides hiding, great. <html> <body> <div id="diva"> <input name="geta" id="geta" type="text" onkeypress="javascript:geta.focus();" onkeyup="javascript:geta.focus();" onblur="javascript:geta.focus();" onchange="javascript:geta.focus();" /> </div> <button onclick="javascript:change();">show/hide div</button> <script language="javascript" type="text/javascript"> <!-- function change() { var div = document.getelementbyid('diva'); if (div.style.display !== 'none') { div.style.display = 'none'; } else { ...

java - contains method of String is not working properly -

i have 1 question not able solve . public static void main(string [] arg) { string description = "this time $fb highest priority"; list<string> list = new arraylist<string>(); list.add("$fb"); list.add("$f"); for(string s : list) { if(description.contains(s)) { system.out.println(s); } } } the out put getting $fb , $f dummy string contains 1 string of list .. other method give exact match ? it looks want see if word contained. can this: set<string> words = new hashset<string>(arrays.aslist(description.split(" "))); ... words.contains(s) ...

java - JFormattedTextField not working correctly -

i have code: jformattedtextfield formattedtextfield = new jformattedtextfield(); formattedtextfield.setbounds(25, 330, 56, 20); contentpanel.add(formattedtextfield); formattedtextfield.setvalue(new double(10.0)); its supposed accepting double numbers, if input character, 's', taken anyway. how can change block make accept keyboard numbers or ','? ignoring other character

java - Behaviour of lastAccessTime BasicFileAttributes.. -

i know should in order change return value of lastaccesstime system.out.println("last access time is:"+basicattributes.lastaccesstime()); system.out.println("last modified time:"+basicattributes.lastmodifiedtime()); even though access file called readattributes on.. lastaccesstime() methods not update value time last accessed file.. using ubuntu , attribute should supported.. what's wrong that? thanks in advance. the operating system isn't obliged update directory every time access file. when close file.

postgresql - Postgres access with www-data and --host argument -

i want access postgres www-data user. command launched cli. my program need able launch command : psql --username www-data --host=127.0.0.1 --dbname=dbname it work if remove --host=127.0.0.1, unfortunately use third party program command , can change it. my pg_hba.conf standard local postgres peer # type database user address method # "local" unix domain socket connections local peer #host www-data 127.0.0.1/32 md5 # ipv4 local connections: host 127.0.0.1/32 md5 # ipv6 local connections: host ::1/128 md5 in postgresql.conf put listen_addresses = '*' yes it's insecure testing everything. still doesn't work in .pgpass 127.0.0.1:5432:*:www-data:password i tried method : peer, ident, md5, passw...

WPF. TextBlock and TextBox aligned properly -

what have when size of border container wide enough: name value namelonger value then size of border gets smaller , have this: name value namelonger v i used wrappanel , achieved this: name value namelonger value it better achieve this: name value namelonger value is possible achieve such thing? not sure if totally understand explaining based on think yiou describing, looking for? <border> <grid> <grid.columndefinitions> <columndefinition width="auto"></columndefinition> <columndefinition width="auto"></columndefinition> </grid.columndefinitions> <grid.rowdefinitions> <rowdefinition height="auto"></rowdefinition> <rowdefinition height="auto"></rowdefinition> </grid.rowdefinitions> <!--put textblocks in here--> </grid> </bord...

c# - Entity framework distinct but not on all columns -

i'd make query through entity framework unions contacts 2 different tables, remove duplicates , orders date. issue i'm having around different dates making same contact appear unique. don't want include date in distinct need afterwards ordering. can't ordering first, remove date , perform distinct, because distinct changes ordering. neither can order before union because doesn't ensure ordering after union. i distinct fields except date, required ordering. ideally pass comparer distinct ef can't translate sql. db.packages.select(p => new recent() { name = p.attention, address1 = p.address1, ... , date = shippingdate }) .concat(db.letters.select(l => new recent() { name = l.addressedto, address1 = p.address1, ..., date = markeddate }) .distinct() .orderbydescending(r => r.date); or problem in sql select distinct attention, address1, shippingdate packages union select addressedto, address1, markeddate letters order shipmentdate desc ...

python - CSV read/write using regex re.sub -

i'd read csv file , recompile using: re.sub('\s+(street|st|trail|trl|tr)\s*$', '', test_file, flags=re.m) i'm getting: typeerror: expected string or buffer when using: import csv reader = csv.reader(open("some.csv", "rb")) row in reader: print row import csv writer = csv.writer(open("some.csv", "wb")) writer.writerows(someiterable) looks need function. have sugestions? you have pass string re.sub() third argument, can line of reader object. can pass writer iterable substitutions: import csv reader = csv.reader(open("input.csv", "rb")) writer = csv.writer(open("output.csv", "wb")) test = '\s+(street|st|trail|trl|tr)\s*$' writer.writerows( (re.sub(test, '', line[0], flags=re.m) line in reader) )

c# - Redirect https to http using rewrite rule in webconfig file -

this have tried far. <rule name="https main site http" stopprocessing="true"> <match url="^(.*)$" ignorecase="true" /> <conditions> <add input="{https}" pattern="off" /> </conditions> <action type="redirect" url="http://{http_host}/{request_uri}" /> </rule> how can redirect https://www.mysite.com http://www.mysite.com this asked long time ago, looks has been answered here: how force https using web.config file . pay close attention 1 of comments mentions query string appended twice if use full answer.

Multiple python loops in same process -

i have project i'm writing in python sending hardware (phidgets) commands. because i'll interfacing more 1 hardware component, need have more 1 loop running concurrently. i've researched python multiprocessing module, turns out hardware can controlled 1 process @ time, loops need run in same process. as of right now, i've been able accomplish task tk() loop, without using of gui tools. example: from tk import tk class hardwarecommand: def __init__(self): # define tk object self.root = tk() # open hardware, set self. variables, call other functions self.hardwareloop() self.udplistenloop() self.eventlistenloop() # start tk loop self.root.mainloop() def hardwareloop(self): # timed processing hardware sethardwarestate(self.state) self.root.after(100,self.hardwareloop) def udplistenloop(self): # listen commands udp, call appropriate functions ...

How can I run a Ruby script from command line and get the response using Java code? -

i need run ruby script using command line java code. for example file in path d:/myproject/myruby.rb i want run file command line , response that. how can achieve this? also, how can return response in myruby.rb caught in command line. you can use this: string[] commands = {"ruby","d:/myproject/myruby.rb"}; runtime rt = runtime.getruntime(); process proc; try { proc = rt.exec(commands); bufferedreader stdinput = new bufferedreader(new inputstreamreader(proc.getinputstream())); string s; while ((s = stdinput.readline()) != null) { system.out.println(s); } } catch (ioexception e) { e.printstacktrace(); }

java - Can't start another activity in Android -

i'm learning android developpement, , wrote short , easy code, doesn't work. can't start activity,despite many try ! here code of main activity : @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_pageaccueil); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.pageaccueil, menu); return true; } public void oncreate1(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_pageaccueil); final button button = (button) findviewbyid(r.id.button1); button.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { intent intent = new intent(pageaccueil.this, devise.class); startactivity(intent); } }); } } and button part of xml layout first/main activity : <button android:...

sql - Within the same group find and exclude records that have the same parent ID for certain types -

i have table following: groupid parentid type 1 abc ind 1 abc ind 1 cde ord 1 efg std 2 zzz ind 2 zzz ind 2 zzz ind 3 yyy cor 3 yyy cor i need exclude records in same group, having same parent id , type ind or cor. need keep groups have different parent id , type not ind or cor. so result want following: groupid parentid type 1 abc ind 1 abc ind 1 cde ord 1 efg std somehow thinking use rank () over(partition groupid order parentid) , won't give me results want. any thoughts? ps: table has 5 million+ records. looking effective way deal it. thanks the following gives list of groupids want exclude select groupid ( select groupid, count(distinct parentid) pcount, count(distinct typecode) tcount, max(typec...

Laravel 4 One To Many relationship Error -

i laravel newbie , trying follow documentation.so have 2 models, 'user' model , 'userphone' model. user has many phones. user model: public function userphone() { return $this->hasmany('userphone'); } userphone model: public function user(){ return $this->belongsto('user'); } on controller trying "copy" documentation: $userphone = user::find(1)->userphone; well result error: trying property of non-object i know missing here , cannot find it. i'm pretty sure don't have user id of 1. $userphone = user::find(1)->userphone; this should work, but, if doesn't find user first part: user::find(1) i return null , null not object, error: trying property of non-object . my advice is, try this var_dump( user::find(1) ); and if receive null, found problem.

skeletal mesh - Looking for skeleton or polygon offset algorithm in R -

Image
i found useful links in question an algorithm inflating/deflating (offsetting, buffering) polygons . sorry - no 'net access sos doesn't work, have implementation of skeleton algorithm in r? edit: generate deflated polygons in stackoverflow link (top image); or seen on http://en.wikipedia.org/wiki/straight_skeleton . gbuffer() , elegant , powerful rgeos package accepts negative values in width argument, returning spatialpolygons 'shrunk' given amount. library(sp) library(rgeos) ## create spatialpolygons object set of x-y coordinates (the hard part!) xy2sp <- function(xy, id=null) { if(is.null(id)) id <- sample(1e12, size=1) spatialpolygons(list(polygons(list(polygon(xy)), id=id)), proj4string=crs("+proj=merc")) } xy <- data.frame(x=c(0,2,3,1,0), y=c(0,0,2,2,0)) sp <- xy2sp(xy) ## shrink spatialpolygons object supplying negative width gbuffer() plot(sp) plot(gbuffer(sp, width=-0.2), add=true, bo...

java - How do I encode the url in below code? -

i looking how escape/encode special characters when passing url in request. public static void senddata(string strval) throws ioexception{ string dosend="https://myhost.com/views?strval="+strval; httpclient httpclient = new defaulthttpclient(); try { system.out.println("inside try"); uribuilder builder = new uribuilder(); system.out.println("builder="+builder); builder.setscheme("http"); builder.sethost("myhost.com").setpath("/views?"); builder.addparameter("strval", strval); system.out.println("add param,sethost,setpath complete"); uri uri = builder.build(); system.out.println("uri="+uri); httpget httpget = new httpget(uri); system.out.println("httpget"+httpget); httpresponse response = httpclient.execute(httpget); system.out.println(response.getstatusline().tostring()); if (response.getstatuslin...